using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Singleton { public class Singleton1 { //优点: // 1.由于实例是在 Instance 属性方法内部创建的,因此类可以使用附加功能(例如,对子类进行实例化), // 即使它可能引入不想要的依赖性。 // 2.直到对象要求产生一个实例才执行实例化;这种方法称为"懒实例化"。 // 懒实例化避免了在应用程序启动时实例化不必要的 singleton。 //缺点: // 在多线程环境下它是不安全的。如果执行过程的不同线程同时进入 Instance 属性方法,那么可能会创建多个 Singleton 对象实例。每个线程都会执行下列语句,并决定必须创建新的实例: // if (instance == null) private static Singleton1 instance; private Singleton1() {//2! } public static Singleton1 Instance { get { if (instance == null) {//1 instance = new Singleton1();//2! } return instance;//3 } } } public sealed class Singleton2 { //这种方法唯一的潜在缺点是,您对实例化机制的控制权较少。 //在 Design Patterns 形式中,您能够在实例化之前使用非默认的构造函数或执行其他任务。 //由于在此解决方案中由 .NET Framework 负责执行初始化,因此您没有这些选项。 //在大多数情况下,静态初始化是在 .NET 中实现 Singleton 的首选方法。 private static readonly Singleton2 instance = new Singleton2();//1! private Singleton2() {//1! } public static Singleton2 Instance { get {//2 return instance; }//3 } } public sealed class Singleton3 { //double-check locking 方法解决了线程并发问题,同时避免在每个 Instance 属性方法的调用中都出现独占锁定。 //它还允许您将实例化延迟到第一次访问对象时发生。 //实际上,应用程序很少需要这种类型的实现。大多数情况下,静态初始化方法已经够用 private static volatile Singleton3 instance; private static object syncRoot = new Object(); private Singleton3() {//2! } public static Singleton3 Instance { get { if (instance == null) {//1 lock (syncRoot) { if (instance == null) instance = new Singleton3();//2! } } return instance;//3 } } } class Program { static void Main(string[] args) { Singleton1 mySingleton1 = Singleton1.Instance; Singleton2 mySingleton2 = Singleton2.Instance; Singleton3 mySingleton3 = Singleton3.Instance; } } }