单例模式回顾

文章目录

  • 单例模式回顾
    • 三要素
    • 变量定义在.cpp 文件中

单例模式回顾

三要素

  • 私有的静态的实例对象 private static instance(一般 单例类的指针)
  • 私有的构造函数(保证在该类外部,无法通过new的方式来创建对象实例) private Singleton(){}
  • 公有的、静态的、访问该实例对象的方法 public static Singleton getInstance(){}(获取单例的方法)
//任意一个.h文件
class Singleton
{
public:
static Singleton *GetInstance();
pricate:
Singleton(){}
~Singleton(){}
static Singleton * instance;
//这里加入你想要单例成员,并在公有属性下写获取方法
}
//对应的.cpp文件
static Singleton::Singleton *GetInstance()
{
	if(instance == NULL)
	{
		instance = new Singleton();
	}
}
Singleton * Singleton::instance = NULL;//另一个关键static 成员初始化

C++ 静态成员的类内初始化 (扩展链接)

变量定义在.cpp 文件中

  • 在.h文件中会编译过程中重复定义
    单例模式(静态变量,非new变量)
    能在适当的时候自动运行构造和析构函数。

/* #include
using namespace std;

class Singleton
{
private:
int test;
Singleton() { cout << “new” < ~Singleton() { cout << “delete” << endl; }

public:
static Singleton *GetInstance()
{
static Singleton singleton;
return &singleton;
}
void SetValue(int v) { test = v; }
int GetValue() { return test; }
};

int main()
{
Singleton *single1 = Singleton::GetInstance();
Singleton *single2 = Singleton::GetInstance();
cout << "value 1: " << single1->GetValue() << endl;
single1->SetValue(100);
cout << "value 2: " << single2->GetValue() << endl;
if( single2 == single1 )
cout << “single1 and single2 is the same object.” << endl;
return 0;
}

你可能感兴趣的:(c++)