1.静态代码块
/// <summary>
/// 静态代码块
/// 仅在第一次调用类的任何成员时自动执行
/// </summary>
public class SingletonStatic
{
private static readonly SingletonStatic _instance =null;
static SingletonStatic()
{
_instance = new SingletonStatic();
}
private SingletonStatic()
{
}
public static SingletonStatic Instance
{
get { return _instance; }
}
}
2.内部类
/// <summary>
/// 内部类
/// </summary>
public class SingletonInner
{
private SingletonInner()
{
}
public static SingletonInner Instance
{
get{ return InnerClass.inner; }
}
private class InnerClass
{
internal static readonly SingletonInner inner = new SingletonInner();
}
}
3.Lazy
/// <summary>
/// Lazy单例
/// </summary>
public class SingletonLazy
{
private static readonly SingletonLazy _instance = new Lazy<SingletonLazy>().Value;
private SingletonLazy()
{
}
public SingletonLazy Instance
{
get { return _instance; }
}
}
/// <summary>
/// https://www.cnblogs.com/zhouzl/archive/2019/04/11/10687909.html
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class Singleton<T> where T : class
{
// 这里采用实现5的方案,实际可采用上述任意一种方案
class Nested
{
// 创建模板类实例,参数2设为true表示支持私有构造函数
internal static readonly T instance = Activator.CreateInstance(typeof(T), true) as T;
}
private static T instance = null;
public static T Instance { get { return Nested.instance; } }
}
class TestSingleton : Singleton<TestSingleton>
{
// 将构造函数私有化,防止外部通过new创建
private TestSingleton() { }
}