标签:
单例模式(Singleton):保证一个类仅有一个实例,并提供一个访问它的全局访问点。
懒汉式:
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; } } }
测试代码:
for(int i=0;i<100;i++) { Task.Run(() => { Singleton s = Singleton.GetInstance(); Console.WriteLine(s.GetHashCode()); }); }
饿汉式:
namespace SingletonDesign { public sealed class Singleton { private static readonly Singleton instance=new Singleton(); private Singleton() { } public static Singleton GetInstance() { return instance; } } }
标签:
原文地址:http://www.cnblogs.com/uptothesky/p/5283815.html