- 单例模式: 确保一个类只有一个实例,并提供一个全局访问点来访问该实例
- 单例模式分为两种:懒汉式和饿汉式。
- 主要角色:单例类
- 静态成员变量
- 获取实例方法
- 私有构造函数
// 懒汉式
class Singleton {
private:
Singleton() {
cout << "Singleton()" << endl;
}
public:
~Singleton() {
cout << "~Singleton()" << endl;
}
static Singleton* getInstance() {
if (m_instance == NULL) {
m_instance = new Singleton;
}
return m_instance;
}
static void freeInstance() {
if (m_instance != NULL) {
delete m_instance;
m_instance = NULL;
}
}
private:
static Singleton* m_instance;
};
懒汉式在对象第一次获取对象的时候才创建对象,好处是在不需要创建对象是不占用内存;
但是每次在获取对象时都需要判断对象是否为空,而且在多线程中有可能会创建多个对象,导致内存泄露,需要加锁,典型结构如下:
static Singleton* getInstance() {
// double check
if (m_instance -- NULL) {
Lock();
if (m_instance == NULL) {
m_instance = new Singletion;
}
Unlock();
}
}
下面是饿汉式的实现代码:
class Singleton {
private:
Singleton() {
cout << "Singleton()" << endl;
}
public:
~Singleton() {
cout << "~Singleton()" << endl;
}
public:
static Singleton* getInstance() {
return m_instance;
}
static void freeInstance() {
if (m_instance != NULL) {
delete m_instance;
m_instance = NULL;
}
}
private:
static Singleton* m_instance;
};
Singleton* Singleton::m_instance = new Singleton;
饿汉式默认就会创建一个静态对象,在获取示例时直接返回该对象即可,缺点就是即使不用也会占用内存,而且线程安全。
测试代码:
int main() {
Singleton* p1 = Singleton::getInstance();
Singleton* p2 = Singleton::getInstance();
cout << p1 << endl;
cout << p2 << endl;
Singleton::freeInstance();
return 0;
}
创建模式(5种)
结构模式(7种)
行为模式(11种)