单例模式是使用最广泛的设计模式之一。顾名思义,单例就是一个类只有一个实例。为什么会要求一个实例呢?一个原因是一个实例能够满足需求,过多实例的存在只会耗费系统资源;另一个原因是为了数据保持一致,多个实例导致数据状态不一致。
实际上,定义一个全局的实例,也算是单例,但无法限制用户再去定义多个。规范的接口定义,有利于限制实例的定义。例如下图中,类的构造函数被私有化,用户就只能通过GetInstance()接口得到实例。
UML类图
代码实例
C++的代码实例如下所示,这是一个简单的例子,如果在多线程的环境下,是需要加锁控制的。
Singleton.h
#ifndef __SINGLETON_H_
#define __SINGLETON_H_
class Singleton
{
public:
static Singleton * GetInstance();
static void DestroyInstance();
private:
Singleton();
static Singleton* m_instance;
};
#endif
Singleton.cpp
#include <iostream>
#include "Singleton.h"
using namespace std;
Singleton* Singleton::m_instance = NULL;
Singleton::Singleton()
{
cout<<"Singleton Constructor"<<endl;
}
Singleton* Singleton::GetInstance()
{
if (m_instance == NULL)
{
m_instance = new Singleton();
}
return m_instance;
}
void Singleton::DestroyInstance()
{
if (m_instance != NULL)
{
delete m_instance;
}
}
main.cpp
#include <iostream>
#include "Singleton.h"
using namespace std;
int main()
{
Singleton* s1 = Singleton::GetInstance();
Singleton* s2 = Singleton::GetInstance();
if (s1 == s2)
{
cout<<"The same"<<endl;
}
Singleton::DestroyInstance();
return 0;
}
更多C++单例可参考
http://blog.csdn.net/hackbuteer1/article/details/7460019