Singleton 模式( 单例模式)
Singleton 模式是设计模式中最为简单、最为常见、最容易实现,也是最应该熟悉和掌握的模式。Singleton 模式就是一个类只创建一个唯一的对象,即一次创建多次使用。
实现单例模式的步骤:
1、构造函数私有化
2、增加静态私有的当前类的指针变量
3、提供静态对外接口,可以让用户获得单例对象
单例分为懒汉式和饿汉式
懒汉式:解决了饿汉式内存浪费问题,但是线程不安全的,可以通过互斥量mutex.lock()和mutex.unlock()来解决
饿汉式:还没有使用该单例对象,该单例对象就已经被加载到内存了,在对象过多时会造成内存浪费
代码:
#include <iostream>
using namespace std;
class A {
public:
static A* getInstace() {
return a;
}
private :
A() {
a = new A;
}
static A* a;
};
A* A::a = NULL;
//懒汉式 对象的创建在第一次调用getInstance函数时创建
//懒汉式是线程不安全的
class SingletonLazy {
public:
static SingletonLazy* getInstance() {
if (pSingleton == NULL) {
pSingleton = new SingletonLazy;
}
return pSingleton;
}
private:
SingletonLazy() {}
static SingletonLazy* pSingleton;
};
//在类外面进行初始化
SingletonLazy* SingletonLazy::pSingleton=NULL;
//饿汉式 对象在程序执行时优先创建
//饿汉式是线程安全的
class SingletonHungry {
public:
static SingletonHungry* getInstance() {
return pSingleton;
}
static void freeSpace() {
if (pSingleton != NULL) {
delete pSingleton;
}
}
private:
SingletonHungry() {}
static SingletonHungry* pSingleton;
};
//以下语句将会在main函数运行前执行
SingletonHungry* SingletonHungry::pSingleton=new SingletonHungry;
void test01() {
SingletonLazy* p1 = SingletonLazy::getInstance();
SingletonLazy* p2 = SingletonLazy::getInstance();
if (p1 == p2) {
cout << "单例模式" << endl;
}
else {
cout << "不是单例模式" << endl;
}
SingletonHungry* p3 = SingletonHungry::getInstance();
SingletonHungry* p4 = SingletonHungry::getInstance();
if (p3 == p4) {
cout << "单例模式" << endl;
}
else {
cout << "不是单例模式" << endl;
}
}
int main()
{
test01();
}
总结:
- Singleton 不可以被实例化,因此将其构造函数声明private
- Singleton 模式经常和 Factory(AbstractFactory)模式在一起使用,因为系统中工厂对象一般来说只要一个