面试题2:C++实现Singleton单例模式
2016-06-06 15:45
459 查看
1.单例模式,在GOF的《设计模式:可复用面向对象软件的基础》中是这样说的:保证一个类只有一个实例,并提供一个访问它的全局访问点。首先,需要保证一个类只有一个实例;在类中,要构造一个实例,就必须调用类的构造函数,如此,为了防止在外部调用类的构造函数而构造实例,需要将构造函数的访问权限标记为protected或private;最后,需要提供要给全局访问点,就需要在类中定义一个static函数,返回在类内部唯一构造的实例。
下面是最简单的情况,单线程的时候,更多具体的解法可参考:http://www.jellythink.com/archives/82
源码:
下面是最简单的情况,单线程的时候,更多具体的解法可参考: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;//会输出10 cout << singletonObj2->GetTest() << endl;//还是会输出10,单例模式下,已经实例化过就不能再实例化 Singleton::DestoryInstance(); system("PAUSE"); return 0; }
相关文章推荐
- C++定义动态数组
- 源码中含有 '\357' '\273' '\277' 处理方法
- C语言的标准和Gcc遵循标准
- 深度探索C++关键字之 virtual
- 栈帧
- 字典树的c++实现
- C++第七次作业
- 第14周项目1--排序函数模板
- C++第七次做作业
- 【C++】 二叉树的基本知识及其遍历
- C语言 定义变量(右左法则)
- C++命名空间实现MD5加密
- C语言解字符串逆序和单向链表逆序问题的代码示例
- C++第七次实验
- C++编译与链接(0)-.h与.cpp中的定义与声明
- 二分查找 C/C++实现
- 2016-06-06-1
- C/C++ typedef用法
- C语言中的static 详细分析
- C++中引用(&)的用法和应用实例