您的位置:首页 > 其它

单件模式(Singleton Pattern)

2008-07-14 11:37 302 查看

一、 单例(Singleton)模式

单例模式的特点:

单例类只能有一个实例。
单例类必须自己创建自己的唯一实例。
单例类必须给所有其它对象提供这一实例。

单例模式应用:

每台计算机可以有若干个打印机,但只能有一个Printer Spooler,避免两个打印作业同时输出到打印机。
一个具有自动编号主键的表可以有多个用户同时使用,但数据库中只能有一个地方分配下一个主键编号。否则会出现主键重复。



二、 Singleton模式的结构:

// Singleton pattern -- Structural example

using System;

// "Singleton"

class Singleton

public class Client

// Singleton pattern -- Real World example

using System;

using System.Collections;

using System.Threading;

// "Singleton"

class LoadBalancer

public class SingletonApp

sealed class Singleton

public sealed class Singleton

Singleton()

}

public static Singleton GetInstance()

return Nested.instance;

}

class Nested

// Explicit static constructor to tell C# compiler

// not to mark type as beforefieldinit

static Nested()

}

internal static readonly Singleton instance = new Singleton();

}

}

这实现了延迟初始化,并具有很多优势,当然也存在一些缺点。详细内容请访问:《Implementing the Singleton Pattern in C#》。文章包含五种Singleton实现,就模式、线程、效率、延迟初始化等很多方面进行了详细论述。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: