※ 單 例 模 式
單例模式是指某一類在被調用時只能創建一個實例,即只能new一次;
※ 餓 漢
在每次調用的時候都先加載;
※ 懶 漢
調用的時候不加載,需要用到再加載;在多線程調用時不安全;
(注意:在Nuity3D中不存在多線程,所以兩種模式都可以用,相對來說,懶漢模式用的多一點)
餓漢模式 C#代碼
1 class HungerSingleton { 2 private static HungerSingleton _hungerSingleton=new HungerSingleton(); 3 4 private HungerSingleton() { } 5 public static HungerSingleton GetInstance() { 6 Console.WriteLine("hunger"); 7 return _hungerSingleton; 8 } 9 }
懶漢模式 C#代碼
1 class LazySingleton { 2 private static LazySingleton _LazySingleton; 3 private LazySingleton() { } 4 public static LazySingleton GetInstance() { 5 if (_LazySingleton==null) 6 { 7 Console.WriteLine("lazy"); 8 _LazySingleton = new LazySingleton(); 9 } 10 return _LazySingleton; 11 } 12 }