用c#的范型实现Singleton模式

以下是完整的代码

 

public partial class Generic_Singleton : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

Response.Write("<p>" + Singleton<TestClass>.Instance.Count + "</p>");

Response.Write("<p>" + Singleton<TestClass>.Instance.Count + "</p>");

Response.Write("<p>" + Singleton<TestClass>.Instance.Count + "</p>");

}

}

 

public class Singleton<T>

{

private static T _instance;

 

public Singleton()

{

 

}

 

public static T Instance

{

get

{

if (_instance == null)

{

_instance = (T)System.Activator.CreateInstance(typeof(T));

}

 

return _instance;

 

}

 

}

}

 

public class TestClass

{

private int count = 0;

 

public int Count

{

get

{

count++;

return count;

}

}

 

}

 

运行结果如下:

1

2

3

 

说明调用的是同一个实例。说明实现了Singleton模式。

 

 

posted on 2007-06-13 13:46  今夜太冷  阅读(638)  评论(1)    收藏  举报