zoukankan      html  css  js  c++  java
  • 面试题2:实现Singleton模式

    书上给的是C#实现,自己写几个C++实现:

    1. 基本版,适用于单线程

     1 class Singleton
     2 {
     3 public:
     4     static Singleton * Instance();
     5     static void Destroy();
     6 protected:
     7     Singleton(){}
     8 private:
     9     static Singleton * m_pInstance;
    10 };
    11 
    12 Singleton * Singleton::m_pInstance = NULL;
    13 
    14 Singleton * Singleton::Instance()
    15 {
    16     if (m_pInstance == NULL)
    17         m_pInstance = new Singleton;
    18     return m_pInstance;
    19 }
    20 
    21 void Singleton::Destroy()
    22 {
    23     delete m_pInstance;
    24 }

    2. 多线程,使用加锁机制

    利用winAPI中的加锁

     1 #include <Windows.h>
     2 
     3 class Locker
     4 {
     5 protected:
     6     friend class Singleton;
     7     CRITICAL_SECTION cs;
     8 
     9 public:
    10     Locker(){
    11         ::InitializeCriticalSection(&cs);
    12     }
    13     void lock(){
    14         ::EnterCriticalSection(&cs);
    15     }
    16     void unlock(){
    17         ::LeaveCriticalSection(&cs);
    18     }
    19     ~Locker(){
    20         ::DeleteCriticalSection(&cs);
    21     }
    22 };
    23 
    24 class Singleton
    25 {
    26 public:
    27     static Singleton * Instance();
    28     static void Destroy();
    29 protected:
    30     Singleton(){}
    31 private:
    32     static Singleton * m_pInstance;
    33 };
    34 
    35 Singleton * Singleton::m_pInstance = NULL;
    36 
    37 Singleton * Singleton::Instance()
    38 {
    39     Locker *lock = new Locker;
    40     lock->lock();
    41     if (m_pInstance == NULL)
    42         m_pInstance = new Singleton;
    43     lock->unlock();
    44     return m_pInstance;
    45 }
    46 
    47 void Singleton::Destroy()
    48 {
    49     delete m_pInstance;
    50 }

    3. 模版实现

     1 class Singleton
     2 {
     3 public:
     4     static T * Instance();
     5     static void Destroy();
     6 protected:
     7     Singleton(){}
     8 private:
     9     static T * m_pInstance;
    10 };
    11 
    12 template <typename T>
    13 T * Singleton<T>::m_pInstance = NULL;
    14 
    15 template <typename T>
    16 T * Singleton<T>::Instance()
    17 {
    18     if (m_pInstance == NULL)
    19         m_pInstance = new T;
    20     return m_pInstance;
    21 }
    22 
    23 template <typename T>
    24 void Singleton<T>::Destroy()
    25 {
    26     delete m_pInstance;
    27 }

    参考资料:

    http://blog.csdn.net/a342374071/article/details/18270643/

    http://www.cnblogs.com/liyuan989/p/4264889.html

  • 相关阅读:
    element 步骤条steps 点击事件
    element-ui的rules中正则表达式
    从master分支创建自己的分支
    2.1 系统调用io实现原理
    2-3形参和实参
    2-2函数
    2-1.编译和链接
    linux高编信号-------setitimer()、getitimer()
    linux高编IO-------有限状态机编程原理(mycpy)
    linux高编线程-------线程同步-条件变量
  • 原文地址:https://www.cnblogs.com/raichen/p/5627063.html
Copyright © 2011-2022 走看看