在 C# 中,一个优秀的线程安全单例通用模板模式应遵循以下原则:
using System;
public class Singleton<T> where T : class
{
private static Lazy<T> _instance = new Lazy<T>(() =>
{
return new T();
});
public static T Instance => _instance.Value;
private Singleton(T initialValue)
{
_instance.Value = initialValue;
}
~Singleton()
{
_instance = null;
}
private static void CheckState()
{
if (typeof(T) == typeof(T) && _instance.IsValueCreated && (_instance.Value == _instance.Value))
{
throw new InvalidOperationException(String.Format("This type '{0}' has been registered multiple times in '{1}'.", typeof(T), typeof(Singleton<T>).AssemblyQualifiedName));
}
}
}
这个模式通过创建一个 Lazy<T>
静态变量 _instance
,实现延迟初始化线程安全的单例类型 T
。同时,通过定义一个构造函数和析构函数进行实例化及资源清理。通过 typeof(T) == typeof(T)
及 _instance.IsValueCreated
来确保单例实例只创建一次。如果 T
类型及其 _instance
发生了更改或重新赋值,则在运行时发生 InvalidOperationException
。当需要创建单例时,可以直接通过 Type T 获取唯一实例:
public class MyClass
{
public MyClass()
{
SingletonFactory.Instance.Instance.StartMethod();
}
}
public class SingletonFactory
{
public static Singleton<MyClass> Instance { get; set; } = new Singleton<MyClass>();
}
该模式采用 Generic
关键字将普通类型转换为 Generic
类型,从而实现单一实例模式。此外,此模式的实例还可以从其他位置 (如数据库、文件、缓存等) 加载或创建。
领取专属 10元无门槛券
手把手带您无忧上云