zoukankan      html  css  js  c++  java
  • Singleton模式笔记

    在C++中,尽量用Singleton替换全局变量是个很好的建议,Singleton一般如下:

    class  CSingleton
    {
    private:
        
    static CSingleton* m_pInstance;
    private:
        CSingleton(){}
        
    ~CSingleton(){}

        CSingleton( 
    const CSingleton& );
        CSingleton
    & operator=const CSingleton& );

    public:
        
    static CSingleton* GetInstance()
        {
            
    if( m_pInstance == NULL )
            {
                m_pInstance 
    = new CSingleton;
            }
            
    return m_pInstance;
        }
    };
    CSingleton
    *  CSingleton::m_pInstance = NULL;
    这种实现有个缺点:单例对象无法销毁.虽然泄漏的内存在程序结束后可由操作系统回收,但是会造成资源泄漏,如网络连接、COM引用等.这些操作系统是无法自动回收的.因此需要在程序结束前销毁这个单例对象.标准C库提供了一个很方便的函数:atexit,通过其注册的函数能在程序结束时自动调用(调用次序是后进先出),可以通过此函数实现单例对象的自动销毁功能:
    class  CSingleton
    {
    private:
        
    static CSingleton* m_pInstance;
    private:
        CSingleton(){}
        
    ~CSingleton(){}

        CSingleton( 
    const CSingleton& );
        CSingleton
    & operator=const CSingleton& );

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

        
    static void Destory()
        {
            
    if( m_pInstance != NULL )
            {
                delete m_pInstance;
                m_pInstance  
    =  NULL;
            }
        }

    };
    CSingleton
    *  CSingleton::m_pInstance = NULL;

    Singleton模式的另一种实现,简称:Meyers 单件,其示例如下:

    class  CSingleton
    {
    private:
        CSingleton(){}
        
    ~CSingleton(){}

        CSingleton( 
    const CSingleton& );
        CSingleton
    & operator=const CSingleton& );

    public:
        
    static CSingleton& GetInstance()
        {
            
    static CSingleton instance;
            
    return instance;
        }
    };
  • 相关阅读:
    Detect Capital
    Maximum Depth of Binary Tree
    Max Consecutive Ones
    Single Number
    Nim Game
    Longest Uncommon Subsequence I
    Average of Levels in Binary Tree
    Next Greater Element I
    Island Perimeter
    Fizz Buzz
  • 原文地址:https://www.cnblogs.com/fangkm/p/1486918.html
Copyright © 2011-2022 走看看