Singleton模式,用于“保证一个类仅有一个实例,并提供一个访问它的全局控制点。”
实现的时候,需要注意:为了避免出现多个实例,构造函数必须为private或protected;而为了让子类可以扩展,构造函数应为protected。为了避免被赋值,把赋值函数也定义为private。
/*
* file: Singleton.h
* brief: Created by night at 2014.04.14
*/
#ifndef __SINGLETON_H__
#define __SINGLETON_H__
class Singleton
{
public:
static Singleton* Instance()
{
if (instance == null) {
// thread lock
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
protected:
Singleton() {}
~Singleton() {}
private:
Singleton(const Singleton &);
Singleton& operator=(const Singleton &);
static Singleton *instance;
};
Singleton* Singleton::instance = NULL;
#endif
PS. 我的设计模式系列blog,《设计模式》专栏,通过简单的示例演示设计模式,对于初学者很容易理解入门。如果需要深入学习,请看GoF的《设计模式》。