单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例类的特殊类。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源。如果希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案。
今天看到这个东西了,就查了些资料。想写的很完善也不是很容易。总结了以下别人的实现方法,挑了两种比较简单的,供和我一样的新手学习。
废话不多说,直接贴代码。
第一种实现:
class Singleton
{
private:
Singleton() {};
Singleton(const Singleton &) {};
Singleton & operator= (const Singleton &) {};
public:
static Singleton *getInstance();
static void destroyInstance();
private:
static Singleton *m_pInstance;
};
Singleton * Singleton::m_pInstance = NULL;
Singleton * Singleton::getInstance()
{
if(m_pInstance == NULL)
m_pInstance = new Singleton;
return m_pInstance;
}
void Singleton::destroyInstance()
{
if(m_pInstance)
delete m_pInstance;
}
第二种实现:
class Singleton
{
private:
Singleton() {};
Singleton(const Singleton &) {};
Singleton & operator= (const Singleton &) {};
public:
static Singleton *getInstance();
static void destroyInstance();
private:
static Singleton *m_pInstance;
};
Singleton * Singleton::m_pInstance = new Singleton();
Singleton * Singleton::getInstance()
{
return m_pInstance;
}
void Singleton::destroyInstance()
{
if(m_pInstance)
delete m_pInstance;
}
第一种实现是在需要的时候创建实例,就是所谓的 懒汉式单例类;第二种实现十预先创建实例,即所谓的 饿汉式单例类。第一种实现是用时间换空间,第二种实现是用空间换时间。还有一点需要注意的是,第一种实现不是线程安全的,即不支持多线程。例如,假如线程A和线程B都检测到m_pInstance为NULL,都去创建实例,则会出现错误。如果需要第一种实现支持多线程,就需要在判断m_pInstance是否为空前加锁,操作完成后解锁,以此来增加对多线程的支持。第二种实现在多线程支持方面则不存在这样的问题。
这两种实现的一个缺点是在用户使用完后需要调用destroyInstance函数去释放生成的实例。