设计模式-单例
1. 單例模式(單線程和多線程)
2. 單例模式的三種寫法
3. 單例模式的優(yōu)缺點和應(yīng)用場景
單例保證了整個進(jìn)程中該對象只被實例化一次
常駐內(nèi)存
普通類型是需要的時候被初始化,用完被GC回收
?
namespace singletonpattern {class SingletonSecond{private SingletonSecond() {Thread.Sleep(1000);//耗時string bigSize = "占用10M內(nèi)存";//耗計算資源string resource = "占用多個線程和數(shù)據(jù)庫連接資源";//耗有限資源Console.WriteLine("{0}被構(gòu)造,線程id={1}", this.GetType().Name, Thread.CurrentThread.ManagedThreadId);}private static SingletonSecond _Singleton = null;/// <summary>/// 靜態(tài)構(gòu)造函數(shù):由CLR保證,在第一次使用這個類之前,調(diào)用并且只調(diào)用一次/// </summary>static SingletonSecond (){_Singleton = new SingletonSecond();}public static SingletonSecond CreateInstance(){return _Singleton;}public void Show(){Console.WriteLine("這里調(diào)用了{(lán)0}.Show", this.GetType().Name);}} } namespace singletonpattern {class SingletonThird{private SingletonThird() {Thread.Sleep(1000);//耗時string bigSize = "占用10M內(nèi)存";//耗計算資源string resource = "占用多個線程和數(shù)據(jù)庫連接資源";//耗有限資源Console.WriteLine("{0}被構(gòu)造,線程id={1}", this.GetType().Name, Thread.CurrentThread.ManagedThreadId);}/// <summary>/// 靜態(tài)變量:會在類型第一次使用的時候初始化,并且只初始化一次/// </summary>private static SingletonThird _Singleton = new SingletonThird();public static SingletonThird CreateInstance(){return _Singleton;}public void Show(){Console.WriteLine("這里調(diào)用了{(lán)0}.Show", this.GetType().Name);}} }?
轉(zhuǎn)載于:https://www.cnblogs.com/xiao9426926/p/6126224.html
總結(jié)
- 上一篇: 交换排序 —— 快速排序
- 下一篇: 【ASP.NET MVC 学习笔记】-