基于静态Singleton模式的使用介绍
什么是静态单例模式?
静态单例模式(static singleton pattern)是我在实践中总结的模式,主要解决的问题是在预先知道某依赖项为单例应用时,通过静态缓存该依赖项来提供访问。当然,解决该问题的办法有很多,这只是其中一个。
实现细节
/// <summary>
/// 静态单例
/// </summary>
/// <typeparam name="tclass">单例类型</typeparam>
public static class singleton<tclass> where tclass : class, new()
{
private static readonly object _lock = new object();
private static tclass _instance = default(tclass);
/// <summary>
/// 获取单例实例
/// </summary>
public static tclass getinstance()
{
return instance;
}
/// <summary>
/// 单例实例
/// </summary>
public static tclass instance
{
get
{
if (_instance == null)
{
lock (_lock)
{
if (_instance == null)
{
_instance = new tclass(); // must be public constructor
}
}
}
return _instance;
}
}
/// <summary>
/// 设置单例实例
/// </summary>
/// <param name="instance">单例实例</param>
public static void set(tclass instance)
{
lock (_lock)
{
_instance = instance;
}
}
/// <summary>
/// 重置单例实例
/// </summary>
public static void reset()
{
lock (_lock)
{
_instance = default(tclass);
}
}
}
应用测试
class program
{
interface iinterfacea
{
string getdata();
}
class classa : iinterfacea
{
public string getdata()
{
return string.format("this is from classa with hash [{0}].", this.gethashcode());
}
}
static void main(string[] args)
{
string data1 = singleton<classa>.getinstance().getdata();
console.writeline(data1);
string data2 = singleton<classa>.getinstance().getdata();
console.writeline(data2);
console.readkey();
}
}
测试结果