1. 单例模式(单线程和多线程)
2. 单例模式的三种写法
3. 单例模式的优缺点和应用场景
单例保证了整个进程中该对象只被实例化一次
常驻内存
普通类型是需要的时候被初始化,用完被GC回收
namespace singletonpattern { /// <summary> /// 1. 私有化构造函数,外部不能用new创建对象 /// 2. 一个私有的静态变量 /// 3. 一个静态的对象创建方法 /// </summary> class Singleton { private Singleton () { Thread.Sleep(1000);//耗时 string bigSize = "占用10M内存";//耗计算资源 string resource = "占用多个线程和数据库连接资源";//耗有限资源 Console.WriteLine("{0}被构造,线程id={1}", this.GetType().Name, Thread.CurrentThread.ManagedThreadId); } private static Singleton _Singleton = null; //单进程时候的单例 //public static Singleton CreateInstance() //{ // if (_Singleton == null) // { // _Singleton = new Singleton(); // } // return _Singleton; //} //多进程下的单例,双重if+lock private static object Singleto_Lock = new object(); public static Singleton CreateInstance() { if (_Singleton == null)//保证对象初始化之后的所有线程,不需要等待锁 { Console.WriteLine("准备进入lock"); lock (Singleto_Lock) //保证只有一个线程进去判断 { Thread.Sleep(1000); if (_Singleton == null) //保证对象为空才真的创建 { _Singleton = new Singleton(); } } } return _Singleton; } public void Show() { Console.WriteLine("这里调用了{0}.Show", this.GetType().Name); } } }
namespace singletonpattern { class SingletonSecond { private SingletonSecond() { Thread.Sleep(1000);//耗时 string bigSize = "占用10M内存";//耗计算资源 string resource = "占用多个线程和数据库连接资源";//耗有限资源 Console.WriteLine("{0}被构造,线程id={1}", this.GetType().Name, Thread.CurrentThread.ManagedThreadId); } private static SingletonSecond _Singleton = null; /// <summary> /// 静态构造函数:由CLR保证,在第一次使用这个类之前,调用并且只调用一次 /// </summary> static SingletonSecond () { _Singleton = new SingletonSecond(); } public static SingletonSecond CreateInstance() { return _Singleton; } public void Show() { Console.WriteLine("这里调用了{0}.Show", this.GetType().Name); } } }
namespace singletonpattern { class SingletonThird { private SingletonThird() { Thread.Sleep(1000);//耗时 string bigSize = "占用10M内存";//耗计算资源 string resource = "占用多个线程和数据库连接资源";//耗有限资源 Console.WriteLine("{0}被构造,线程id={1}", this.GetType().Name, Thread.CurrentThread.ManagedThreadId); } /// <summary> /// 静态变量:会在类型第一次使用的时候初始化,并且只初始化一次 /// </summary> private static SingletonThird _Singleton = new SingletonThird(); public static SingletonThird CreateInstance() { return _Singleton; } public void Show() { Console.WriteLine("这里调用了{0}.Show", this.GetType().Name); } } }