设计模式之单实例模式(Singleton)

原理:将类的构造函数由pubic变为private或者protect,添加获取对象的public 成员函数,返回指向对象的静态指针。

首先来一段简单的代码实现

代码一

class Singleton
{
public:
static Singleton* instance()
{
	if (pInstance == NULL)
	{
		return new Singleton();
	}
	return pInstance;
}
protected:
	Singleton()
	{

	}
private:
	static Singleton* pInstance;
};
Singleton* Singleton::pInstance = NULL;

 上述代码存在内存泄露的问题,由于这个对象是由类本身自己构造的,依据c++对象释放的原则,在哪里创建就在哪里释放的原则,类本身自己需要释放这个对象,如果交给了客户去释放则会造成野指针的情况,虽然智能指针解决了内存泄露的问题,但是没有解决内存野指针的问题。如果在整个程序运行期间多个指针指向堆内存,就会造成野指针的现象,但是单实例模式采用的是静态只能指针,即在整个程序运行完成之后才会释放堆内存可以满足要求,无需share_ptr。

代码二

#include <stdio.h>
#include <memory>
#include "iostream"
using namespace std;

class Singleton
{
public:
static Singleton* instance()
{
	if (ptrInstance.get() == NULL)
	{
			ptrInstance.reset(new Singleton());
	}
	return ptrInstance.get();
}
protected:
	Singleton()
	{

	}
private:
	//static Singleton* pInstance;
	static auto_ptr<Singleton> ptrInstance;
};
auto_ptr<Singleton> Singleton::ptrInstance;

 

posted @ 2013-07-18 11:15  l851654152  阅读(213)  评论(0编辑  收藏  举报