單例模式(c 實現)

2022-01-10 04:31:38 字數 1495 閱讀 3413

單例模式使我們使用非常多的模式,也是很簡單的乙個設計模式。

單例模式通過私有化類的建構函式來避免外部建立該類的例項,僅僅提供乙個靜態的getinstace()方法來獲取在類內部建立的乙個全域性唯一的例項,同時在該方法種建立唯一例項,還要保證建立過程是執行緒安全的。

單例模式的使用場景可以從他的特性來分析,比如:

windows的畫圖工具,畫筆是單例,但是畫布是我們可以隨意建立的。我們可以改變畫筆的顏色和粗細,但是我們用來畫出圖案的畫筆例項永遠是同乙個;

也可以把一些通用的方法放到乙個commonn類裡面定義成static的方法,這樣我們就可以通過common的單例來呼叫這些方法,當然簡單的使用全域性函式也是可以滴~。這裡的單例就更多的是貢獻了它的封裝特性;

draw.h

#include #include "singleton.h"

class draw

;

draw.cpp

#include #include "draw.h"

draw::draw(std::string name)

:m_name(name)

void draw::show()

std::cout << std::endl;

}}

properties.h

#include struct properties

;

singleton.h

#include "properties.h"

class pen

;

singleton.cpp

#include "singleton.h"

pen *pen::getinstance()

void pen::setproperty(const properties &proty)

std::string pen::draw()

pen::pen()

main.cpp

#include #include #include "singleton.h"

#include "properties.h"

#include "draw.h"

using namespace std;

int main()

); std::thread t2(());

std::thread t3(());

t1.join();

t2.join();

t3.join();

return 0;

}

C 實現單例模式

給所需要進行單例的類ctest的建構函式宣告為private或者protected 防止在類外隨意生成ctest的物件 然後宣告乙個靜態成員變數 instance 乙個靜態成員函式getinsance staticctest getinstance staticctest instance 靜態成員...

C 實現單例模式

ifndef singleton h define singleton h include include using namespace std class locker inline locker inline void lock inline void unlock private pthre...

C 實現單例模式

class singleton 私有建構函式 singleton const singleton 拷貝建構函式,只宣告不定義,這要當使用者或友元想要拷貝構造該類的已存在例項時會出錯。singleton operator const singleton 賦值運算子,只宣告不定義,作用同上 public...