文章速览
- 概述
- 直上代码
坚持记录实属不易,希望友善多金的码友能够随手点一个赞。
共同创建氛围更加良好的开发者社区!
谢谢~
概述
懒汉单例的创建模式,需要创建的单例直接继承该类即可。
直上代码
public abstract class SingletonBase<T>where T : class{/// <summary>/// Static instance. Needs to use lambda expression/// to construct an instance (since constructor is private)./// </summary>private static readonly Lazy<T> sInstance = new Lazy<T>(() => CreateInstanceOfT());/// <summary>/// Gets the instance of this singleton./// </summary>public static T Instance{get { return sInstance.Value; }}/// <summary>/// Creates an instance of T via reflection since T's constructor is expected to be private./// </summary>/// <returns>T.</returns>private static T CreateInstanceOfT(){return Activator.CreateInstance(typeof(T), true) as T;}}