保证一个类仅有一个实例,并提供一个访问它的全局访问点。
两个实用的实现方式:
1. 静态初始化
1 public sealed class Singleton
2 {
3 private static readonly Singleton instance = new Singleton();
4
5 private Singleton()
6 {
7 }
8
9 public static Singleton Instance
10 {
11 get
12 {
13 return instance;
14 }
15 }
16 }
2 {
3 private static readonly Singleton instance = new Singleton();
4
5 private Singleton()
6 {
7 }
8
9 public static Singleton Instance
10 {
11 get
12 {
13 return instance;
14 }
15 }
16 }
该类标记为 sealed 以阻止发生派生,而派生可能会增加实例.
公共语言运行库负责处理变量初始化,是线程安全的。
在大多数情况下,静态初始化是在 .NET 中实现 Singleton 的首选方法。
如果你的静态类比较多或是比较大,对性能有要求,可以用下面的方法
2 . 静态延迟初始化
public sealed class Singleton
{
private Singleton()
{
}
public static Singleton Instance
{
get
{
return Child.instance;
}
}
private class Child
{
static Child()
{
}
internal static Singleton instance = new Singleton();
}
}
{
private Singleton()
{
}
public static Singleton Instance
{
get
{
return Child.instance;
}
}
private class Child
{
static Child()
{
}
internal static Singleton instance = new Singleton();
}
}
初始化工作有Child类的一个静态成员来完成,这样就实现了延迟初始化.<
/span>