[TOC]
模式要点
- 某个类只能有一个实例
- 它必须自行创建这个实例
- 它必须自行向整个系统提供这个实例
具备私有构造函数类
的单例模板
public abstract class Singleton<T> where T : class
{
private static class Holder
{
static Holder() { }
internal static readonly Lazy<T> instance = new Lazy<T>(() =>
{
//添加了异常处理,以便在实例化失败时抛出详细的异常信息。
try
{
return Activator.CreateInstance(typeof(T), true) as T;
}
catch (Exception ex)
{
throw new InvalidOperationException($"The {typeof(T)} instance could not be created.", ex);
}
});
}
public static T Instance
{
get
{
return Holder.instance.Value;
}
}
protected Singleton()
{
//检查 Holder.instance.IsValueCreated,如果实例已经被创建,则抛出异常。这可以防止通过反射创建多个实例。
if (Holder.instance.IsValueCreated)
{
throw new InvalidOperationException("An instance of this singleton class has already been created.");
}
}
}
开闭原则的倾斜性
;
所有的具体享元类都是在同一个层次上独立的,没有任何共享状态;
存在一些对象是组合的,一个复合享元对象中包含多个单纯享元对象,每个单纯享元对象都是共享同一个外部状态的;