面试题2:实现Singleton模式
2016-06-30 10:31
302 查看
书上给的是C#实现,自己写几个C++实现:
1. 基本版,适用于单线程
2. 多线程,使用加锁机制
利用winAPI中的加锁
3. 模版实现
参考资料:
http://blog.csdn.net/a342374071/article/details/18270643/ http://www.cnblogs.com/liyuan989/p/4264889.html
1. 基本版,适用于单线程
class Singleton { public: static Singleton * Instance(); static void Destroy(); protected: Singleton(){} private: static Singleton * m_pInstance; }; Singleton * Singleton::m_pInstance = NULL; Singleton * Singleton::Instance() { if (m_pInstance == NULL) m_pInstance = new Singleton; return m_pInstance; } void Singleton::Destroy() { delete m_pInstance; }
2. 多线程,使用加锁机制
利用winAPI中的加锁
#include <Windows.h> class Locker { protected: friend class Singleton; CRITICAL_SECTION cs; public: Locker(){ ::InitializeCriticalSection(&cs); } void lock(){ ::EnterCriticalSection(&cs); } void unlock(){ ::LeaveCriticalSection(&cs); } ~Locker(){ ::DeleteCriticalSection(&cs); } }; class Singleton { public: static Singleton * Instance(); static void Destroy(); protected: Singleton(){} private: static Singleton * m_pInstance; }; Singleton * Singleton::m_pInstance = NULL; Singleton * Singleton::Instance() { Locker *lock = new Locker; lock->lock(); if (m_pInstance == NULL) m_pInstance = new Singleton; lock->unlock(); return m_pInstance; } void Singleton::Destroy() { delete m_pInstance; }
3. 模版实现
class Singleton { public: static T * Instance(); static void Destroy(); protected: Singleton(){} private: static T * m_pInstance; }; template <typename T> T * Singleton<T>::m_pInstance = NULL; template <typename T> T * Singleton<T>::Instance() { if (m_pInstance == NULL) m_pInstance = new T; return m_pInstance; } template <typename T> void Singleton<T>::Destroy() { delete m_pInstance; }
参考资料:
http://blog.csdn.net/a342374071/article/details/18270643/ http://www.cnblogs.com/liyuan989/p/4264889.html
相关文章推荐
- 海量数据处理面试题集锦与Bit-map详解
- JAVA程序员面试总结,高手整理加强版
- 面试总结
- 三大框架ssh的面试该聊的内容
- 今天开始进入程序员的世界
- Maria840js面试题:不使用中间变量,交换int型的 a, b两个变量的值
- android面试题目
- 【工作】面试和工作
- 程序员必知的六种隔离技术
- android(base)面试题
- 前端面试题汇总
- 一道无关编程的面试题
- 一道有趣的面试题,小鸟和火车的问题
- 嘴上说要认真面试,身体却在偷懒,这样好么?
- 成为Java顶尖程序员 ,看这11本书就够了
- 成为一个优秀程序员的11条小贴士
- 黑马程序员——面向对象
- java 面试题三十三 子类父类方法执行顺序的问题
- 我是进击的码农4
- 野生程序员初长成——记北大程序设计与算法专项课程