MSDN 上有解释泛型是什么: C#泛型简介 。今天我就用泛型重构我的代码。以前每个类的单例模式是这么写的:
以前的单例模式代码
public class myClass
{
public myClass(){}
private static myClass m_instance = null;
private static object sync = new object();
public static myClass Instance
{
if(m_instance == null){
lock(sync){
m_instance = new myClass();
}
}
return m_instance;
}
}
{
public myClass(){}
private static myClass m_instance = null;
private static object sync = new object();
public static myClass Instance
{
if(m_instance == null){
lock(sync){
m_instance = new myClass();
}
}
return m_instance;
}
}
要是每个类都有这么段代码,该如何.....我能不能将其抽出来为一个公共方法? 有了泛型的基础,我们很容易地做到。以下是泛型的单例提供者,它要求类必须实现一个可以 new 的对象:
泛型单例的实现
/// <summary>
/// 单例模式
/// </summary>
/// <typeparam name="T"></typeparam>
public class SingletonProvider<T> where T : new()
{
private static T m_instance;
private static readonly object sync = new object();
private SingletonProvider() { }
/// <summary>
/// 用法:SingletonProvider<myclass>.Instance 获取该类的单例
/// </summary>
public static T Instance
{
get
{
if (m_instance == null)
{
lock (sync)
{
if (m_instance == null)
{
Console.WriteLine("创建了一个对象 ");
m_instance = new T();
}
}
}
return m_instance;
}
}
}
/// 单例模式
/// </summary>
/// <typeparam name="T"></typeparam>
public class SingletonProvider<T> where T : new()
{
private static T m_instance;
private static readonly object sync = new object();
private SingletonProvider() { }
/// <summary>
/// 用法:SingletonProvider<myclass>.Instance 获取该类的单例
/// </summary>
public static T Instance
{
get
{
if (m_instance == null)
{
lock (sync)
{
if (m_instance == null)
{
Console.WriteLine("创建了一个对象 ");
m_instance = new T();
}
}
}
return m_instance;
}
}
}
下面我新建一个测试类:
测试类
class SingletonTest
{
public SingletonTest() { }
public string Name
{ get; set; }
public void Show() {
Console.WriteLine("{0} 呼叫 {1}", DateTime.Now, Name);
}
}
{
public SingletonTest() { }
public string Name
{ get; set; }
public void Show() {
Console.WriteLine("{0} 呼叫 {1}", DateTime.Now, Name);
}
}
主程序中调用方法:
主程序调用
class Program
{
static void Main(string[] args)
{
SingletonProvider<SingletonTest>.Instance.Name = "感恩的心";
SingletonProvider<SingletonTest>.Instance.Show();
SingletonProvider<SingletonTest>.Instance.Name = "infozero@163.com";
SingletonProvider<SingletonTest>.Instance.Show();
Console.Read();
}
}
{
static void Main(string[] args)
{
SingletonProvider<SingletonTest>.Instance.Name = "感恩的心";
SingletonProvider<SingletonTest>.Instance.Show();
SingletonProvider<SingletonTest>.Instance.Name = "infozero@163.com";
SingletonProvider<SingletonTest>.Instance.Show();
Console.Read();
}
}
运行结果如下:
个人的一点体会:泛型是将类型参数化,它是将指定的类型推迟到客户端实现,有点类似于 模板方法。
转自:http://www.cnblogs.com/infozero/archive/2010/07/04/1770753.html
家家有老人
人人会变老
帮老就是帮未来的您