单例模式应该是我接触设计模式时最早学会的一个设计模式,它比较简单易懂,目的就一个,设计出能只能创建一个对象的类。
上代码:
singleton.h
<span style="font-size:14px;">//singleton.h
#ifndef _SINGLETON_H__
#define _SINGLETON_H__
#include <iostream>
class singleton
{
private:
static singleton *_instance;
public:
static singleton *Instance();
protected:
singleton();
};
#endif //_SINGLETON_H__
</span>
singleton.cpp
<span style="font-size:14px;">//singleton.cpp
#include "singleton.h"
using namespace std;
singleton *singleton::_instance = 0;
singleton::singleton()
{
cout<<"singleton created!"<<endl;
}
singleton *singleton::Instance()
{
if (_instance == 0)
_instance = new singleton();
return _instance;
}
</span>
main.cpp
<span style="font-size:14px;">//main.cpp
#include "singleton.h"
int main(int argc, char **argv)
{
singleton *pOne = singleton::Instance();
}
</span>
关键技术在于将singleton类的构造函数不公开,而是通过一个静态函数去调用构造函数,这样构造函数就成为透明的了,设计者能够通过一个静态函数来操控它,比如,用另个一个静态成员属性来计数,client只能得到singleton的静态函数这个唯一的接口。
本模式的UML图比较简单,暂不给出。