一、单例模式简介(Bref Introduction)
单例模式(Singleton Pattern),保证一个类只有一个实例,并提供一个访问它的全局访问点。单例模式因为Singleton封装它的唯一实例,它就可以严格地控制客户怎样访问它以及何时访问它。
二、单例模式在第一次用到的时候初始化
1、Singleton
class ImplFactory
{
public:
static ImplFactory *getInstance()
{
if (_instance == 0)
{
_instance = new ImplFactory();
}
return _instance;
}
Implementor *getImplementor(int type)
{
if (type == 0)
{
return new ConcreImplementorA();
}
return new ConcreImplementorB();
}
private:
ImplFactory(){}
static ImplFactory *_instance;
};
2、Client
ImplFactory::getInstance()->getImplementor(_type);