C++ 单例模式是与工厂模式相对应的, 也是设计模式中最常用的一种模式, 主要面向工具类,基本不用存储太多的跟自身有关的数据,在这种情况下,每次都去new一个对象,即增加了开销,也使得代码更加复杂,如果使用全局的存储,会影响封装性,而我们又期待可以只有一个实例使用,将默认构造函数与析构函数 声明为私有的,这样就不会被外部创建对象, 并且,也可以自己回收,
Singleton* getInstance()
{
if
(instance == NULL)
instance =
new
Singleton();
return
instance;
}
Singleton* getInstance()
{
Lock()
if
(instance == NULL)
instance =
new
Singleton();
Unlock()
return
instance;
}
这样每次都会判断是否加锁, 会造成性能的下降, 线程的阻塞严重,
可以通过双重加锁
Singleton* getInstance()
{
if
(instance == NULL) {
Lock()
if
(instance == NULL)
instance =
new
Singleton();
Unlock()
}
return
instance;
}