在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
静态变量public sealed class Singleton { private Singleton() { } private static readonly Singleton singleInstance = new Singleton(); public static Singleton GetInstance { get { return singleInstance; } } } 静态构造函数public class SingletonSecond { private static SingletonSecond _SingletonSecond = null; static SingletonSecond() { _SingletonSecond = new SingletonSecond(); } public static SingletonSecond CreateInstance() { return _SingletonSecond; } } 延迟加载public sealed class Singleton { private Singleton() {} private static readonly Lazy<Singleton> Instancelock = new Lazy<Singleton>(() => new Singleton()); public static Singleton GetInstance { get { return Instancelock.Value; } } } 对应的泛型方式
public abstract class SingletonStatic<T> where T:class,new() { private static T instance = null; static SingletonStatic() { instance = new T(); } public static T GetInstance() { return instance; } } public class SingletonSafe<T> where T : class, new() { private static T _instance; private static readonly object syslock = new object(); public static T GetInstance() { //线程安全锁 if (_instance == null) { lock (syslock) { if (_instance == null) { _instance = new T(); } } } return _instance; } } public abstract class Singleton<T> where T:class,new() { private static T instance; public static T GetInstance() { if (instance == null) instance = new T(); return instance; } } 使用: public class GlobalConfiguration : SingletonStatic<GlobalConfiguration> {....}
|
请发表评论