面试题2:C++实现Singleton单例模式

来源:互联网 发布:唐诗宋词朗诵软件 编辑:程序博客网 时间:2024/06/05 09:21

1.单例模式,在GOF的《设计模式:可复用面向对象软件的基础》中是这样说的:保证一个类只有一个实例,并提供一个访问它的全局访问点。首先,需要保证一个类只有一个实例;在类中,要构造一个实例,就必须调用类的构造函数,如此,为了防止在外部调用类的构造函数而构造实例,需要将构造函数的访问权限标记为protected或private;最后,需要提供要给全局访问点,就需要在类中定义一个static函数,返回在类内部唯一构造的实例。

下面是最简单的情况,单线程的时候,更多具体的解法可参考:http://www.jellythink.com/archives/82

源码:

/*单例模式最简单的版本*/#include <iostream>using namespace std;class Singleton{public:static Singleton *GetInstance(int temp){if (m_Instance == NULL){m_Instance = new Singleton(temp);}return m_Instance;}static void DestoryInstance(){if (m_Instance != NULL){delete m_Instance;m_Instance = NULL;}}// 测试输出成员变量的值int GetTest(){return m_Test;}private:Singleton(int temp){ m_Test = temp; }static Singleton *m_Instance;int m_Test;};Singleton *Singleton::m_Instance = NULL;int main(int argc, char *argv[]){Singleton *singletonObj = Singleton::GetInstance(10);Singleton *singletonObj2 = Singleton::GetInstance(11);cout << singletonObj->GetTest() << endl;//会输出10cout << singletonObj2->GetTest() << endl;//还是会输出10,单例模式下,已经实例化过就不能再实例化Singleton::DestoryInstance();system("PAUSE");return 0;}



0 0
原创粉丝点击