设计模式:单例模式
单例模式(Singleton):保证一个类仅有一个实例,并提供一个访问它的全局访问点。
懒汉式:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
namespace SingletonDesign { public class Singleton { private static Singleton instance; private static readonly object syncRoot = new object(); private Singleton() { } public static Singleton GetInstance() { if(instance==null) { lock (syncRoot) { if (instance == null) { instance = new Singleton(); } } } return instance; } } }
测试代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
for(int i=0;i<100;i++) { Task.Run(() => { Singleton s = Singleton.GetInstance(); Console.WriteLine(s.GetHashCode()); }); }
饿汉式:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
namespace SingletonDesign { public sealed class Singleton { private static readonly Singleton instance=new Singleton(); private Singleton() { } public static Singleton GetInstance() { return instance; } } }