C#单例模式的懒汉与饿汉
生活随笔
收集整理的這篇文章主要介紹了
C#单例模式的懒汉与饿汉
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
※ 單 例 模 式
? ? 單例模式是指某一類在被調用時只能創建一個實例,即只能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 }?
轉載于:https://www.cnblogs.com/RainPaint/p/9890154.html
總結
以上是生活随笔為你收集整理的C#单例模式的懒汉与饿汉的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【luogu P1558 色板游戏】 题
- 下一篇: Java安全管理器――SecurityM