单件模式是一种设计模式,即保持同时只能创建一个实例,下面列出了C#实现单件模式的三种方法
方法1
public sealed Class Singleton { private static ReadOnly Singleton instance = new Singleton(); private Singleton(){} public static Singleton Instance { get { return instance; } } }
方法2
public sealed Class ClassicSingleton { private static ClassicSingleton instance; private static object SyncRoot = new Object (); private ClassicSingleton(){} public static ClassicSingleton Instance { get { if(instance == null) { lock (SyncRoot) { if(instance == null) { instance = new ClassicSingleton (); } } } return instance; } } }
方法3
public Class Singleton { private static Singleton instance; // Added a static mutex for synchronising use of instance. private static System.Threading.Mutex mutex; private Singleton(){} static Singleton () { instance = new Singleton(); mutex = new System.Threading.Mutex(); } public static Singleton Acquire() { mutex.WaitOne (); return instance; } // Each call to Acquire () requires a call to Release() public static void Release() { mutex.ReleaseMutex(); } }