立博名家

设计模式之单件模式

本文介绍了C#下关于单例的三种实现方法。

  最普通的一种:

以下是引用片段:
using System;
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
instance = new Singleton();
return instance;
}
}
}

  这种方案在.net下面是线程不安全的,每个线程进来会创建不同的类型实例。

  下面是一种在.Net公共语言运行环境下的线程安全单例实现模式:

以下是引用片段:
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get
{
return instance;
}
}
}

posted on 2008-04-11 23:48  大李  阅读(132)  评论(0)    收藏  举报

导航

立博名家