什么是单例模式 使用泛型实现单例提供者
使用泛型实现单例提供者
介绍 很多有着不同开发背景得人都会比较熟悉单例模式 他们会发现每次他们要创建一个不同的单例类的时候 都不得不写同样得代码 使用新的C# 的泛型 可以实现只写一次同样得代码 背景 已经有很多文章介绍过单例模式 也许最完整的一个C#版本在这里可以找到: Implementing the Singleton Pattern in C# 也有越来越多介绍C#泛型得文章 例如 一篇由CodeProject的Ansil所写的文章可以在这里找到: Generics in C# 使用 C# 泛型来完成单例模式的重用 使用 C# 的泛型 使得实现我所说的 单例提供者 成为可能 这是一个可用来创建单例类实例确不需要为每个特定的类重写单例模式代码的可重用的类 这样分离出单例结构的代码 将有利于保持按单例模式使用类或不按单例模式使用类的灵活性 在这里使用的单例的代码是基于文章上面提到过的 Implementing the Singleton Pattern in C# 文章里的第五个版本实现的public sealed class Singleton { Singleton() { } public static Singleton Instance { get { return SingletonCreator instance; } } class SingletonCreator { // Explicit static constructor to tell C# piler // not to mark type as beforefieldinit static Nested() { } internal static readonly Singleton instance = new Singleton(); } }
基于对泛型的了解 你可以发现没有理由不在这段代码里替换类型参数为泛型里典型的 T 如果这样做 这段代码就变成下面这样public class SingletonProvider where T : new() { SingletonProvider() { } public static T Instance { get { return SingletonCreator instance; } } class SingletonCreator { static SingletonCreator() { } internal static readonly T instance = new T(); } }
注意在这里使用了泛型的约束 这个约束强制任何类型 t 都必须具有无参数的公共构造函数 这里允许singletoncreator类来实例化类型 t
那么 要怎么样来使用单例提供者呢?为了弄清除如何使用它 我们需要写一个测试类 这个测试类有两个部分 第一部分是一个默认的构造函数 用来设置timestamp变量的值 第二部分是一个公共函数 用来实现用 debug writeline 来输出timestamp的值 这个测试类的意思就是不论那个线程在任何时候 在单例下调用这个类公共方法 都将返回相同的值
public class TestClass { private string _createdTimestamp; public TestClass () { _createdTimestamp = DateTime Now ToString(); } public void Write() { Debug WriteLine(_createdTimestamp); } } 这个类就像下面这样使用单例提供者 SingletonProvider Instance Write();

lishixinzhi/Article/program/net/201311/11650