单例模式

in 未分类

有时,我们需要在应用程序中只允许存在一个类的实例。
如windows的任务管理器,永远只可能出现一个,这就是典型的单例模式。
单例模式提供一个全局的访问点,并且让外部无法对该类进行new()
典型的单例模式版本:


public sealed class Singleton
{
static Singleton instance=null;
Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}

但这并不是一个好的代码,因为这样的代码不是安全的,很可能被其它线程修改。

第二个版本:

public sealed class Singleton
{
static Singleton instance=null;
static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
}

使用了lock关键字,确保只能有一个线程可以访问它。

更完整的说明:

http://www.yoda.arachsys.com/csharp/singleton.html

2 Comments

2 Comments

  1. 这。。。。

  2. [quote=下一秒]
    这。。。。

    刷屏者:Kill:D

Leave a Reply

Using Gravatars in the comments - get your own and be recognized!

XHTML: These are some of the tags you can use: <a href=""> <b> <blockquote> <code> <em> <i> <strike> <strong>