您的位置:首页 > 编程语言 > C#

Using C# 2.0 Generics to achieve a reusable Singleton pattern

2014-11-07 14:15 453 查看
一般代码:

public sealed class Singleton
{
Singleton()
{
}

public static Singleton Instance
{
get
{
return SingletonCreator.instance;
}
}

class SingletonCreator
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}

internal static readonly Singleton instance = new Singleton();
}
}用模板实现:
public class SingletonProvider <T> where T:new()
{
SingletonProvider() {}

public static T Instance
{
get { return SingletonCreator.instance; }
}

class SingletonCreator
{
static SingletonCreator() { }

internal static readonly T instance = new T();
}
}用例:
public class TestClass
{
private string _createdTimestamp;

public TestClass ()
{
_createdTimestamp = DateTime.Now.ToString();
}

public void Write()
{
Debug.WriteLine(_createdTimestamp);
}
}使用:
SingletonProvider<TestClass>.Instance.Write();
原地址:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: