在线客服
在线客服系统
 2011招生简章 |  高中生专区 | 自考生专区 | 大学生专区 | 白领专区

C# “Singleton” 模式四种实现方法

点击数: 更新时间:2010-05-27 11:32:33
 

北大青鸟网上学院:大家一定用过或者看过“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 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();

  }

  }

  优点:既节省资源,又简单明了,线程也安全了(一箭三雕)

  缺点:轻微冗长
 


友情提示:如果您对北大青鸟的学费、课程、就业有任何疑问,可以拨打免费 4006-010-802 和我们沟通!

相关信息
没有相关内容
开班信息

日期 班级 类型 余座
4月29日 S1151 脱产班 9
4月15日 S1150 脱产班 3
3月30日 S1149 脱产班 已满
3月22日 S1148 脱产班 已满
3月20日 S1146 脱产班 已满
3月15日 S1144 脱产班 已满
3月11日 S1143 脱产班 已满
2月19日 S1142 脱产班 已满

 

免费试听
讲座时间: 2011年4月16日
讲座地点:
阜成门校区第二教室
讲座内容: 揭秘木马
主讲老师: 杨校长
讲师介绍: 计算机专业,10年软件开发与培训经验,任中软集团项目经理;独立设计和负责多个大型企业应用,有丰富实践经验并精通北大青鸟ACCP教学培训体系。
咨询电话: 010-68351302
订座电话: 010-68351303

 

©Copyright2004 - 2009 www.bjaccp.com, All Rights Reserved
版权所有2004-2008 北大青鸟APTECH( 北京佳音旗舰 ) 授权培训中心
地址:北京西城区北礼士路100号( 阜成门华联商厦西门北侧北走50米)100037北大青鸟地址
京ICP备06064589号
51.la