//线程不安全的单例模式 public class Singleton { private static Singleton singleton = null; public static Singleton Single { get { if (singleton == null) { singleton = new Singleton(); return singleton; } else return singleton; } } private Singleton() { } } //线程安全的单例模式,双重锁定 public class ThreadSafeSingleton { private static ThreadSafeSingleton threadSafeSingleton; private static readonly object synRoot = new object(); public static ThreadSafeSingleton getInstance() { if (threadSafeSingleton == null) { lock (synRoot) { if (threadSafeSingleton == null) { threadSafeSingleton = new ThreadSafeSingleton(); } } return threadSafeSingleton; } else { return threadSafeSingleton; } } private ThreadSafeSingleton() { } } //恶汉模式的单例模式,依赖公共语言库来初始化变量 //这种静态初始化的方式是在自己被加载时就将自己实例化,所以形象的称为饿汉式单例类 public class SafeSingleton { private static SafeSingleton singleton = new SafeSingleton(); private SafeSingleton() { } public static SafeSingleton getInstance() { return singleton; } }