单例模式C++实现

2014-11-24 07:27:25 · 作者: · 浏览: 0

前一段时间看自学了设计模式,发现好多书的java实现的。因为本人是从事C++开发的,因此想尝试用C++自己实现一遍,加深理解。不足之处还望大神们赐教。

单例模式

定义:确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。

适用性:当类只能有一个实例。这种情况应该很常见,所以单例模式也是个人觉得最常用的简单设计模式之一了。

优点:

1、 对唯一实例的受控访问

2、 缩小名空间

3、 运行操作和表示的精化

4、 运行可变数目的实例

5、 比类操作更灵活。

实现:

class Singleton

{

public:

staticSingleton *GetInstance();

voiddoSomething();

protected:

private:

Singleton(){}

staticSingleton *m_pInstance;

};

Singleton*Singleton::m_pInstance = NULL;

Singleton*Singleton::GetInstance()

{

if(m_pInstance == NULL)

{

m_pInstance = new Singleton;

}

returnm_pInstance;

}

voidSingleton::doSomething()

{

cout<<"doSomething..."<

}

原始版,设计模式书上就是这么个例子。大部分情况下都是没有问题的,但是如果类中有打开句柄之类,那就必须显示的析构。需要delete m_pInstance。针对此问题可以

class Singleton

{

public:

static Singleton * GetInstance() ;

private:

Singleton (){}

static Singleton * m_pInstance;

classCleaner {

public:

~Cleaner()

{

if (Singleton::m_pInstance)

delete Singleton::m_pInstance;

}

};

static Cleaner cleaner;

} ;

当然这都是只能是在单线程的情况下,没有考虑并发的情况。

classSingleton {

public:

static Singleton& Instance() {

static Singleton theSingleton;

return theSingleton;

}

private:

Singleton();

Singleton(Singleton const&);

Singleton& operator=(Singleton const&);

~Singleton();

};

这是网上看到有大神给出的优化的代码。个人比较喜欢这种实现方式。

扩展:运行类有有限个实例。例如副主席副经理之类的都是可以有多个实例的

classVicePreisdent

{

public:

enum{MAX = 3};

static VicePreisdent &GetInstance()

{

if (instanceVec.size() == 0)

{

for (size_t i = 0; i

{

VicePreisdent*president = new VicePreisdent(i);

instanceVec.push_back(president);

}

}

int num = rand() % MAX;

return *(instanceVec[num]);

}

void doSomething()

{

cout<<"Preisdent number:"<

}

protected:

private:

VicePreisdent(int val):number(val)

{}

~VicePreisdent();

VicePreisdent(VicePreisdent &);

VicePreisdent& operator=(VicePreisdent&);

static vector instanceVec;

int number;

};

vector VicePreisdent::instanceVec;

int_tmain(int argc, _TCHAR* argv[])

{

for (int i = 0; i < 10 ;++i)

{

VicePreisdent &president =VicePreisdent::GetInstance();

president.doSomething();

}

system("pause");

return 0;

}

\