Singleton模式的.NET实现

Windows Mobile下使用Native C++开发日志类文章中dpol提问 “在C#下面怎么应用Singleton模式呢?”。下面写一下Singleton模式的.NET实现。

 

public sealed class Logger : IDisposable
{
//the Singleton Implement
// Static members are lazily initialized.
// .NET guarantees thread safety for static initialization
public static readonly Logger Instance = new Logger();

private Logger()
{
}

public void Dispose()
{
}
}

这个实现还是保证三个需求: 1. 有且只有一个对象实例化。 2.多线程的控制。3. 按需实例化。

sealed class 保证Singleton类不能被继承。什么时候中国人这个类变成 sealed 就好,不用老是被代表

static Logger Instance 保证按需实例化和多线程安全。

private Logger()  保证只有一个对象实例化。

 

很简单吧。

 

 修改记录:

1.根据回复增加 readonly 到定义中。

posted @ 2010-02-25 07:23  Jake Lin  阅读(1170)  评论(7编辑  收藏  举报