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#程序设计有所帮助。

你可能感兴趣的:(C#实现单件模式的三种常用方法)