基于静态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();
}
}
测试结果