保证一个类仅有一个实例,并提供一个访问它的全局访问点。
1.示例1.
由于加了readonly关键字,所以只会在构造函数中初始化一次.
public sealed class Singleton { // Private Constructor Singleton() { } // Private object instantiated with private constructor static readonly Singleton instance = new Singleton(); // Public static property to get the object public static Singleton UniqueInstance { get { return instance;} } }
2.延迟初始化
注意内部多定义了一个类
public class Singleton { // Private constructor Singleton () { } // Nested class for lazy instantiation class SingletonCreator { static SingletonCreator () {} // Private object instantiated with private constructor internal static readonly Singleton uniqueInstance = new Singleton(); } // Public static property to get the object public static Singleton UniqueInstance { get {return SingletonCreator.uniqueInstance;} } }
这个模式平时用到的也最多,面试的人也很喜欢问这个,属于基本模式,简单也不容易忘记,自然大家都喜欢问,呵呵