1、单例模式
- 需求的提出
在架构设计时,某些类在整个系统生命期中最多只能有一个对象存在(Single Instance)。
提出问题:如何定义一个类,使得这个类最多只能创建一个对象?
解析:
- 要控制类的数目,必须对外隐藏构造函数
- 思路
— 将构造函数的访问属性设置为 private
— 定义 instance(标识符) 并初始化为 NULL
— 当需要使用对象时,访问 instance 的值
1、空值:创建对象,并用 instance 标记
2、非空值:返回 instance 标记的对象
#include <iostream>
#include <string>
using namespace std;
class Test
{
static Test* c_instance;
Test()
{
}
Test(const Test& obj);
Test& operator = (const Test& obj);
public:
static Test* GetInstance()
{
if (c_instance == NULL)
{
c_instance = new Test();
}
return c_instance;
}
void print()
{
cout << "this = " << this << endl;
}
};
Test* Test::c_instance = NULL;
int main()
{
Test* a1 = Test::GetInstance();
Test* a2 = Test::GetInstance();
Test* a3 = Test::GetInstance();
a1->print();
a2->print();
a3->print();
return 0;
}
分析:
从结果我们可以看出,定义不同的指针都指向一个对象,这就是单例模式的效果。单例模式的对象不用 delete。
2、单例类模板
- 单例模式存在的问题
— 需要使用单例模式时:
1、必须定义静态变量 c_instance
2、必须定义静态成员函数 GetInstance
所以我们有改进的地方,把它定义成一个单例类模板: - 解决方案:将单例模式相关的代码抽取出去,开发单例类模板。当需要单例类模板时,直接使用单例类模板。
Singleton.h
#ifndef _SINGLETON_H_
#define _SINGLETON_H_
#pragma once
template <typename T>
class singleton
{
static T* c_instance;
public:
static T* GetInstance();
};
template <typename T>
T* singleton<T>::c_instance = NULL;
template <typename T>
T* singleton<T>::GetInstance()
{
if (c_instance == NULL)
{
c_instance = new T();
}
return c_instance;
}
#endif
main.cpp
#include <iostream>
#include <string>
#include "Singleton.h"
using namespace std;
class Test
{
friend class singleton<Test>; //当前类需要使用单例模式
Test()
{
}
Test(const Test& obj);
Test& operator = (const Test& obj);
public:
void print()
{
cout << "this = " << this << endl;
}
};
int main()
{
Test *ts1 = singleton<Test>::GetInstance();
Test *ts2 = singleton<Test>::GetInstance();
Test *ts3 = singleton<Test>::GetInstance();
ts1->print();
ts2->print();
ts3->print();
return 0;
}
小结:
- 单例模式是开发中最常用的设计模式之一
- 单例模式的应用使得一个类最多只有一个对象
- 可以将单例模式相关的代码抽象成类模板
- 需要使用单例模式的类直接使用单例模板