创建型模式
单例模式(Singleton)
意图:保证一个类只有一个实例,并提供一个访问它的全局访问点。
比如任务管理器就只需要一个实例。
如何来实现呢?可以把类的构造方法隐藏起来,设为private,然后类自身提供一个静态方法去获取实例。
实现:
#include <iostream>
using namespace std;
class Singleton {
private :
Singleton() {
cout << "create a instance" << endl;
}
static Singleton * _instance;
public :
static Singleton * getInstance();
};
Singleton * Singleton::_instance = NULL;
Singleton * Singleton::getInstance() {
if(_instance == NULL) {
_instance = new Singleton();
}
return _instance;
}
int main() {
Singleton * t1 = Singleton::getInstance();
Singleton * t2 = t1->getInstance();
Singleton & ref = * Singleton::getInstance();
delete t1;
return 0;
}
这个代码存在三个问题:
1. 复制构造函数、等号运算没有隐藏起来,还是会创建对象。比如
Singleton a;
Singleton b(a), c = a; 这是可以的
2. 线程不安全
3. 删除实例的时候,需要自己手动删除,而且很容易出错,不容易管理。
解决办法:
用static变量的特点,只初始化一次。
"
在C++memory model中对static local variable,说道:The initialization of such a variable is defined to occur the first time control passes through its declaration; for multiple threads calling the function, this means there’s the potential for a race condition to define first.
"
#include <iostream>
using namespace std;
class Singleton {
private :
Singleton() {
cout << "create a instance" << endl;
}
Singleton & operator = (const Singleton &);
Singleton(const Singleton &);
public :
~Singleton() {
cout << "destory" << endl;
}
static Singleton * getInstance();
};
Singleton * Singleton::getInstance() {
static Singleton instance;
return &instance;
}
int main() {
Singleton * t1 = Singleton::getInstance();
Singleton * t2 = t1->getInstance();
Singleton & ref = * Singleton::getInstance();
return 0;
}