設計模式 單例模式

2021-10-06 23:15:53 字數 867 閱讀 5312

單例模式

單例 singleton 是設計模式的一種,其特點是只提供唯一乙個類的例項,具有全域性變數的特點,在任何位置都可以通過介面獲取到那個唯一例項;

特點全域性只有乙個例項:static 特性,同時禁止使用者自己宣告並定義例項(把建構函式設為 private)

執行緒安全

禁止賦值和拷貝

使用者通過介面獲取例項:使用 static 類成員函式

實現**

#include

class

singleton

singleton

(const singleton&)=

delete

; singleton&

operator=(

const singleton&)=

delete

;static singleton&

get_instance()

private

:singleton()

};intmain

(int argc,

char

*ar**)

通過區域性靜態變數的特性保證了執行緒安全 (c++11, gcc > 4.3, vs2015支援該特性);

不需要使用共享指標,**簡潔;

注意在使用的時候需要宣告單例的引用 single& 才能獲取物件。

另外網上有人的實現返回指標而不是返回引用

static singleton*

get_instance()

這樣做並不好,理由主要是無法避免使用者使用delete instance導致物件被提前銷毀。還是建議大家使用返回引用的方式。

設計模式 單例模式

單例模式 singleton pattern 是乙個比較簡單的模式,其定義如下 ensure a class has only one instance,and provide a golbal point of acess to it.確保某乙個類只有乙個例項,而且自行例項化並且向整個系統提供這個...

設計模式 單例模式

class testsingleton static public function instance return self testsingleton private function clone public function setsinvar sinvar public function ...

設計模式 單例模式

單例模式的目的是保證類在系統中只被例項化一次,由該唯一的例項來為系統提供服務.單例模式主要用於保證服務的統一,比如獲取統一的編號服務,模仿oracle的序列生成等.但單例的使用需要謹慎,特別是在需要作負載均衡的地方,因為這種程式級的單例模式實際上只能保證在乙個應用中為單例.如果被多個應用載入,還是會...