熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

C# “Singleton” 模式四種實現方法

2013-11-13 09:59:59  來源: .NET編程 

  大家一定用過或者看過Singleton模式了吧

  下面給出三種實現方法分別給出優缺點

  方法一

  public sealed class Singleton

  {

  private static readonly Singleton instance = new Singleton();

  private Singleton(){}

  public static Singleton Instance

  {

  get

  {

  return instance;

  }

  }

  }

  優點簡單明了

  缺點耗費資源

  方法二

  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)

  {

  //custom code

  instance = new ClassicSingleton();

  }

  }

  }

  return instance;

  }

  }

  }

  優點節省資源

  缺點代碼冗長

  方法三

  public sealed class Singleton

  {

  static Singleton(){Instance = new Singleton();}

  private Singleton(){}

  public static Singleton Instance{get; private set;}

  }

  優點既節省資源又簡單明了

  缺點線程不安全

  方法四

  public class Singleton

  {

  private static Singleton instance;

  // Added a static mutex for synchronising use of instance

  private static SystemThreadingMutex mutex;

  private Singleton() { }

  static Singleton()

  {

  instance = new Singleton();

  mutex = new SystemThreadingMutex();

  }

  public static Singleton Acquire()

  {

  mutexWaitOne();

  return instance;

  }

  // Each call to Acquire() requires a call to Release()

  public static void Release()

  {

  mutexReleaseMutex();

  }

  }

  優點既節省資源又簡單明了線程也安全了(一箭三雕)

  缺點輕微冗長


From:http://tw.wingwit.com/Article/program/net/201311/12245.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.