单件模式:生成且仅生成类的一个实例。
C++示例代码如下:
#include "stdafx.h"
/*
* CONTENTS: DESIGN PATTERN, SINGLETON PATTERN
* AUTHOR: YAO H. WANG
* TIME: 2013-11-1 23:16:05
* EDITION: 1
*
* ALL RIGHTS RESERVED!
*/
class Singleton1
{
private:
static Singleton1 *uniqueInstance;
Singleton1()
{
}
public:
//单线程下使用
static Singleton1* getInstance()
{
if(NULL == uniqueInstance)
uniqueInstance = new Singleton1();
return uniqueInstance;
}
};
class Singleton2
{
private:
static Singleton2 uniqueInstance;
Singleton2()
{
}
public:
//可适用于多线程
static Singleton2 getInstance()
{
return uniqueInstance;
}
};
void main()
{
Singleton1 *s1 = Singleton1::getInstance();
Singleton2 s2 = Singleton2::getInstance();
}