单例模式,顾名思义,整个代码只有一个。如类。如果采用单例模式,则需要在静态数据区域上分配个内存,提供给整个程序。他得自己创建整个类实例。
单例模式的使用步骤:
a) 构造函数私有化。// 为不让在类的外部再创建一个本类的实例
b) 提供一个全局的静态方法(全局访问点)来获取单例对象。
c) 在类中定义一个静态指针,指向本类的变量的静态变量指针 。
例子如下所示
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
/*
class A
{
public:
private:
A() {
}
};
*/
/*
一是某个类只能有一个实例;
二是它必须自行创建这个实例;
三是它必须自行向整个系统提供这个实例。
*/
/*
单例模式的使用步骤:
a) 构造函数私有化。// 为不让在类的外部再创建一个本类的实例
b) 提供一个全局的静态方法(全局访问点)来获取单例对象。
c) 在类中定义一个静态指针,指向本类的变量的静态变量指针 。
*/
class Singleton
{
public:
static Singleton* getInstance()
{
return instance;
}
private:
//不让类的外部再创建实例
Singleton() {
}
static Singleton* instance;//指向本类唯一实例的指针。
};
/*
饿汉式 - 在编译期间就已经确定这个唯一的实例了。
*/
Singleton* Singleton::instance = new Singleton; //类的内部
class Singleton2
{
public:
static Singleton2* getInstance()
{
//加锁
if (instance == NULL) {
instance = new Singleton2;
}
//关锁
return instance;
}
private:
Singleton2() {
}
static Singleton2 * instance;
};
//懒汉式的初始化方式
Singleton2 *Singleton2::instance = NULL;
int main(void)
{
Singleton * s1 = Singleton::getInstance();
Singleton *s2 = Singleton::getInstance();
if (s1 == s2) {
cout << "s1 == s2" << endl;
}
else {
cout << "s1 != s2 " << endl;
}
Singleton2 *s3 = Singleton2::getInstance();
Singleton2 *s4 = Singleton2::getInstance();
if (s3 == s4) {
cout << "s3 == s4" << endl;
}
else {
cout << "s3 != s4" << endl;
}
return 0;
}
如下:打印机的例子(写日志)
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using namespace std;
class Printer
{
public:
static Printer *getInstance() {
return instance;
}
void print(string text)
{
cout << "打印的内容是" << text << endl;
sequence++;
cout << "今天已经打印了 " << sequence << "条数据" << endl;
}
static int getCnt() {
return sequence;
}
private:
Printer() {
}
//垃圾回收工
class Garbo {
private:
~Garbo() {
if (instance != NULL) {
delete instance;
}
}
};
static Garbo garbo; //在静态区域开辟一个对象, garbo
static int sequence; //记录打印机已经打印了多少条数据。
static Printer* instance;
};
int Printer::sequence = 0;
Printer* Printer::instance = new Printer;
Printer::Garbo Printer::garbo;
int main(void)
{
//员工1 获取
Printer *p1 = Printer::getInstance();//获取到唯一的打印机实例
p1->print("一份简历");
Printer *p2 = Printer::getInstance();
p2->print("lol 皮肤");
Printer *p3 = Printer::getInstance();
p3->print("离职申请");
return 0;
}
来源:https://www.cnblogs.com/strangemonkey/p/12551663.html