C#实现单件模式的三种常用方法
本文实例讲述了C#实现单件模式的三种常用方法。分享给大家供大家参考。具体分析如下:
单件模式是一种设计模式,即保持同时只能创建一个实例,下面列出了C#实现单件模式的三种方法
方法1
publicsealedClassSingleton { privatestaticReadOnlySingletoninstance=newSingleton(); privateSingleton(){} publicstaticSingletonInstance { get { returninstance; } } }
方法2
publicsealedClassClassicSingleton { privatestaticClassicSingletoninstance; privatestaticobjectSyncRoot=newObject(); privateClassicSingleton(){} publicstaticClassicSingletonInstance { get { if(instance==null) { lock(SyncRoot) { if(instance==null) { instance=newClassicSingleton(); } } } returninstance; } } }
方法3
publicClassSingleton { privatestaticSingletoninstance; //Addedastaticmutexforsynchronisinguseofinstance. privatestaticSystem.Threading.Mutexmutex; privateSingleton(){} staticSingleton() { instance=newSingleton(); mutex=newSystem.Threading.Mutex(); } publicstaticSingletonAcquire() { mutex.WaitOne(); returninstance; } //EachcalltoAcquire()requiresacalltoRelease() publicstaticvoidRelease() { mutex.ReleaseMutex(); } }
希望本文所述对大家的C#程序设计有所帮助。