描述:单例模式要求一个类仅有一个实例,并且提供了一个全局的访问点。
方式一(推荐)
/// <summary> /// 单例模式,静态初始化 /// sealed:密封类,不可被继承,防止子类被实例化而不能保证只有一个实例。 /// private Singleton():用private修改构造函数,防止类在外部被实例。 /// static readonly:表示只能在声明时赋值,或是在静态构造中赋值。 /// </summary> public sealed class Singleton { private static readonly Singleton instance = new Singleton(); private Singleton() { } public static Singleton getInstance() { return instance; } }
方式二(不推荐)加锁费资源
/// <summary> /// 单例模式,加锁双层判空,延迟加载 /// </summary> public sealed class Singleton2 { private static Singleton2 instance; private Singleton2() { } private static readonly object obj = new object(); public static Singleton2 getInstance() { if (instance == null) { lock (obj) { if (instance == null) { instance = new Singleton2(); } } } return instance; } }
方式三(推荐)
/// <summary> /// 单例模式,静态初始化,延迟加载 /// </summary> public sealed class Singleton3 { public Singleton3() { } public static Singleton3 Instance { get { return Delay.DelayInstance; } } public sealed class Delay { private static readonly Singleton3 delayInstance = new Singleton3(); private Delay() { } public static Singleton3 DelayInstance { get { return delayInstance; } } } }
应用场景:Windows任务管理器、windows回收站、网站的计数器、日志应用、WebConfig对象的读取、数据库连接池、多线程的线程池、HttpApplication
参考:
http://www.cnblogs.com/Terrylee/category/36516.html
http://www.cnblogs.com/Terrylee/archive/2005/12/09/293509.html