C#完成單件形式的三種經常使用辦法。本站提示廣大學習愛好者:(C#完成單件形式的三種經常使用辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#完成單件形式的三種經常使用辦法正文
本文實例講述了C#完成單件形式的三種經常使用辦法。分享給年夜家供年夜家參考。詳細剖析以下:
單件形式是一種設計形式,即堅持同時只能創立一個實例,上面列出了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(); } }
願望本文所述對年夜家的C#法式設計有所贊助。