1.簡單解釋:在創建對象時,無論創建多少次,在堆空間上只會申請一次記憶體空間。 2.例子(1): 例子(2): 例子(3): ...
1.簡單解釋:在創建對象時,無論創建多少次,在堆空間上只會申請一次記憶體空間。
2.例子(1):
public class Singleton{ private static Singleton _singleton = null; //鎖 private static Object singleton_lock = new Object(); //構造函數私有化 private Singleton(){ //初始化代碼 } public static Singleton CreateInstance(){ if(_singleton == null) //先看看是否初始化過,避免每次進入都要判斷鎖 { lock(_singleton_lock){ //防止多個線程進入 if(_singleton == null){ //判斷單例對象是否為null _singleton = new Singleton(); } } } return _singleton; } }
例子(2):
public class Singleton{ private static Singleton _singleton = null; //構造函數私有化 private Singleton(){ //初始化代碼 } //靜態構造函數 static Singleton(){ _singleton = new Singleton(); } public static Singleton CreateInstance(){ return _singleton; } }
例子(3):
public class Singleton{ private static Singleton _singleton = new Singleton(); //構造函數私有化 private Singleton(){ //初始化代碼 } public static Singleton CreateInstance(){ return _singleton; } }