設計模式 21 單例模式

2021-06-26 15:35:29 字數 1641 閱讀 1025

宣告:vs2012中已經支援c++11了,因此下面的程式在vs2012中可以執行。如果版本比2012低,可能因為不支援:std::mutex,std::shared_ptr而失敗。

#ifndef singleton_h

#define singleton_h

#include #include using namespace std;

/*關鍵:

1 雙重檢查機制:

//先判斷如果第一次建立,然後枷鎖,然後在判斷是否為空,例項化;如果一進入就加鎖,那麼效率不好;

//如果判斷完了再進入加鎖,那麼多個程序仍然會多次例項化,

if(0 == _instance.get())

singleton(const singleton& ){}

~singleton(void){}

singleton& operator = (const singleton& ){}

public:

//static t* instance();

static t* instance()

}return _instance.get();

}private:

static std::shared_ptr_instance;//靜態成員函式,指向該類的指標;注意這裡定義的實際上是乙個型別t的指標

static std::mutex _mutex; //獨佔物件

};templateshared_ptrsingleton::_instance;

templatemutex singleton::_mutex;

/*宣告單例模式類的型別,使:指標和單例類成為友元類*/

#define declare_singleton_class(type) \

friend class shared_ptr< type > ; \

friend class singleton< type > ;

#endif

下面是乙個使用示例:service.h檔案

#ifndef servicemanger_h

#define servicemanger_h

#include "singleton.h"

#include class servicemanger

//注意,不能宣告為私有,否則報錯

servicemanger(void);

~servicemanger(void);

};typedef singletonssmanger;

#endif

service.cpp

#include "servicemanger.h"

servicemanger::servicemanger(void)

servicemanger::~servicemanger(void)

main.cpp檔案

#include #include "servicemanger.h"

using namespace std;

int main(int argc,char* argv)

21種設計模式之 單例模式

單例模式 使用場合 適合乙個類中只有乙個例項的情況。比如任務管理器。單例模式的必要要素 a 私有的建構函式 b 私有的靜態靜態字段 c 以自己為返回值靜態 公共的方法 單例在使用場景的不同又分為了餓漢單例和懶漢單例模式 餓漢單例模式在類的載入時就把類的例項交給了引用 懶漢單例模式只有取得類的例項方法...

2 1 單例模式

皇帝與臣子 乙個類只能生成乙個物件 皇帝 其他所有類對這個物件的依賴都是同乙個,體現到 上如下 author zephyr description 定義乙個私有的構造器,emperor自己可以new乙個物件,但其他類不能new當前物件,其他類只能通過靜態的getinstance方法獲取emperor...

2 1單例模式

物件資料型別的作用 把描述同乙個事物 同乙個物件 的屬性和方法放在乙個記憶體空間下,起到了分組的作用,這樣不同事物之間的屬性即使屬性名相同,相互也不會發生衝突 我們把這種分組編寫 的模式叫做 單例模式 在單例模式中我們把person1和person2也叫做 命名空間 var person1 var ...