設計模式學習系列1 單例模式

爲何學習單例模式,由於單例模式用的比較普遍,遊戲客戶端的配置文件讀取類,服務器日誌類等等,都是使用單例模式來實現,單例模式也便是保證類只有一個實例,而且訪問類全局的接口,這種方法可使用全局來實現,但不能保證只存在一個,最好的辦法是類中作限制,如今單例模式的實現方法有兩種,一種稱爲餓漢式,類加載的時候就初始化,另一種是懶漢式,在使用的時候建立對象html

1懶漢模式指針版本設計模式

class singletonP
 {
     //類中默認生成的 構造函數,copy構造函數,賦值設置爲私有變量 
 private:
     singletonP(){str = "懶漢模式 使用指針注意釋放問題哦";}
     ~singletonP(){};    // 析構的時候不會調用 
    static singletonP * pSingle ;
    string str ;
    
    class CGarbo   //它的惟一工做就是在析構函數中刪除singletonP的實例  
    {  
    public:  
        ~CGarbo()  
        {  
            if(singletonP::pSingle)  
                delete singletonP::pSingle;  
        }  
    };  
    static CGarbo Garbo;  //定義一個靜態成員變量,程序結束時,系統會自動調用它的析構函數  
public: 
//    ~singletonP();    
    // 得到類方法的接口,在第一次使用的時候建立 
    static singletonP* GetSingletonP() 
    {
        if(pSingle == NULL)       //多線程狀況下須要雙重鎖定 
                pSingle = new singletonP() ;
        return pSingle ; 
    }
    
    void printNum()
    {
        cout << str << "\n" << endl ;            
    }
 };

這種寫法須要注意釋放問題,由於靜態變量和全局變量同樣實在系統結束的時候系統釋放,利用這個特徵,建一個局部類,專門用來釋放須要師範的參數安全

2懶漢模式靜態局部變量
class singletonA
 {
     //類中默認生成的 構造函數,copy構造函數,賦值設置爲私有變量 
 private:
     singletonA()
     {
        str = "局部變量懶漢模式" ;    
    }  
    ~singletonA()
    {
        
    } 

    singletonA(const singletonA& single);
    singletonA operator=(const singletonA& single);        
    string str ; 
public:
    // 得到類方法的接口,在第一次使用的時候建立 
    static singletonA* GetSingletonA()
    {
        static singletonA SingleClass;
        return &SingleClass ; 
    }
    
    void printNum()
    {
        cout << str << "\n" << endl ;            
    }
 };

這種方法是用的比較多的,其中構造函數,賦值函數所有私有化,只提供局部靜態的返回接口服務器

3餓漢模式多線程

class singletonE
 {
     //類中默認生成的 構造函數,copy構造函數,賦值設置爲私有變量 
 private:
     singletonE()
     {
        str = "餓漢模式注意多線程中的鎖哦";    
    }  
    ~singletonE()
    {
        
    } 
    static singletonE SingleClass ;
    string str ;
public:
    
    static singletonE* GetSingletonE()
    {
        return &SingleClass ; 
    }
    
    void printNum()
    {
        cout << str << "\n" << endl ;            
    }
 };

4單例模式總結函數

對於線程安全,還有一種雙重鎖的寫法學習

單例模式使用靜態變量,若是出現互相之間的調用須要注意初始化順序等問題spa

能夠參考的文章:.net

懶漢模式線程

最優單例模式

Technorati 標籤: 設計模式
相關文章
相關標籤/搜索