zoukankan      html  css  js  c++  java
  • 单例模式

    懒汉模式

    lazy load,只有在使用的时候才会进行初始化

    class CSingleton  
    {  
    private:  
       CSingleton(){} 
       static CSingleton *m_pInstance;  
    public:  
       static CSingleton * GetInstance()  
       {  
           if(m_pInstance == NULL) 
               m_pInstance = new CSingleton();  
           return m_pInstance;  
       }  
    };  
    

    改进1

    懒汉模式中m_pInstance指向的空间没有得到释放,利用程序在结束时自动析构全局变量以及所有的类的静态成员变量特性,在单例类中添加内存回收的类

    class CSingleton  
    {  
    private:  
       CSingleton(){}  
       static CSingleton *m_pInstance;  
       class CGarbo  
       {  
       public:  
           ~CGarbo()  
           {  
               if(CSingleton::m_pInstance)  
                   delete CSingleton::m_pInstance;  
           }  
       };  
       static CGarbo Garbo; 
    public:  
       static CSingleton * GetInstance()  
       {  
           if(m_pInstance == NULL)  
               m_pInstance = new CSingleton();  
           return m_pInstance;  
       }  
    };  
    

    改进2

    懒汉模式不是线程安全,考虑双重加锁,

    static CCriticalSection cs;  
    static CSingleton * GetInstance()  
    {  
      if(m_pInstance == NULL) 
      { 
            Lock lock(cs);  
            if(m_pInstance == NULL)
            m_pInstance = new CSingleton();  
      }
      return m_pInstance;  
    }  
    

    饿汉模式

    加载之初就将自己实例化,因此是线程安全的

    class CSingleton  
    {  
    private:  
        static CSingleton *m_pInstance = new CSingleton();
        CSingleton(){}  
    public:  
        static CSingleton * GetInstance()  
        {    
            return instance;  
        }  
    };  
    

    无锁的线程安全的懒汉形式

    将返回的实例对象定义成GetInstance函数的静态局部变量

    class Singleton
    {
    public:
        static Singleton* GetInstance()
        {
            static Singleton *instance = new Singleton();
            //cout << instance << endl;
            return instance;
        }
    private:
        Singleton(){}
    };
    

    PS:NS3中采用此方法实现单例模板

    template <typename T>
    class Singleton : private NonCopyable
    {
    public:
      static T *Get (void) {
       static T object;
       return &object;
    };
    
    
  • 相关阅读:
    jQuery 选择城市,显示对应的即时时区时间
    HTML5 LocalStorage 本地存储,刷新值还在
    jQuery 鼠标拖拽移动窗口
    css/css3常用收集/笔记
    Linux下删除命令 硬盘空间查看... 常用命令
    linux 下 zip unzip压缩与解压
    js字节转换、字节转换GB等
    jquery 判断网络图片,或网络文件是否存在
    js中substr,substring,indexOf,lastIndexOf,split 的用法
    apktool、dex2jar、jd-gui的区别及详解
  • 原文地址:https://www.cnblogs.com/rainySue/p/dan-li-mo-shi.html
Copyright © 2011-2022 走看看