設計模式 單例模式

2021-09-24 02:28:04 字數 1012 閱讀 7174

1.餓漢式:在類初始化時建立

public class singletondemo 

private static singletondemo instance = new singletondemo();

public static singletondemo getinstance()

}

2.懶漢式:雙重判斷加鎖

public class singletondemo 

private static singletondemo instance = null;

public static singletondemo getinstance()

}} return instance;

}}

這種方式可能會有問題,當乙個執行緒執行到instance = new singletondemo();時候,另乙個執行緒獲取例項,可能獲取到null,

例項化物件分為三步;

1.記憶體開闢新空間

2.例項化物件

3.物件指向記憶體位址

在這過程中可能出現重排序,即第2、 3步互換,導致另乙個執行緒獲取的例項為null;

解決方式加上volatile關鍵字:private static volatile singletondemo instance = null; 防止重排序

也可以在靜態**塊中例項化,這個要注意順序:

private static singletondemo instance = null;

static

3.列舉方式:

public class singletondemo 

public static singletondemo getinstance()

private enum singleton

public singletondemo getinstance()

}}

設計模式 單例模式

單例模式 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的序列生成等.但單例的使用需要謹慎,特別是在需要作負載均衡的地方,因為這種程式級的單例模式實際上只能保證在乙個應用中為單例.如果被多個應用載入,還是會...