标签:
第一种:
public sealed class Singleton1 { private static Singleton1 instance; private Singleton1() { } public static Singleton1 Instance { get { if (instance == null) { instance = new Singleton1(); } return instance; } } }
第二种:
public sealed class Singleton2 { private static readonly Singleton2 instance = new Singleton2(); private Singleton2() { } public static Singleton2 Instance { get { return instance; } } }
第三种:
public sealed class Singleton3 { private static volatile Singleton3 instance = null; private static object syncRoot = new object(); private Singleton3() { } public static Singleton3 Instance { get { if (instance == null) { lock (syncRoot) { if (instance == null) { instance = new Singleton3(); } } } return instance; } } }
第四种:
public sealed class Singleton4 { //因为下面声明了静态构造函数,所以在第一次访问该类之前,new Singleton4()语句不会执行 private static readonly Singleton4 _instance = new Singleton4(); static Singleton4() { } private Singleton4() { } public static Singleton4 Instance { get { return _instance; } } }
第五种:
public sealed class Singleton5 { private Singleton5() { } public static Singleton5 Instance { get { return Nested._instance; } } private class Nested { static Nested() { } internal static readonly Singleton5 _instance = new Singleton5(); } }
第六种:
public sealed class Singleton6 { private static readonly Lazy<Singleton6> _instance = new Lazy<Singleton6>(() => new Singleton6()); private Singleton6() { } public static Singleton6 Instance { get { return _instance.Value; } } }
第七种,先是一个抽象的单例类:
/// <summary> /// 1.声明抽象类,以便不能直接使用,必须继承该类才能用 /// 2.使用Lazy<T>作为_instance,T就是我们要实现单例的继承类 /// 3.根据微软的文档和单例特性,单例类的构造函数必须是私有的,所以这里要加相应的验证 /// 4.一旦验证通过,就invoke这个私有的无参构造函数 /// 5.Instance属性返回唯一的一个T的实例 /// </summary> /// <typeparam name="T"></typeparam> public abstract class Singleton7<T> { private static readonly Lazy<T> _instance = new Lazy<T> ( () => { var ctors = typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); if (ctors.Count() != 1) { throw new InvalidOperationException(string.Format("Type {0} must have exactly one constructor.", typeof(T))); } var ctor = ctors.SingleOrDefault(c => c.GetParameters().Count() == 0 && c.IsPrivate); if (ctor == null) { throw new InvalidOperationException(string.Format("The constructor for {0} must be private and take no parameters", typeof(T))); } return (T)ctor.Invoke(null); } ); public static T Instance { get { return _instance.Value; } } }
继承上面抽象类的子类:
class MySingleton : Singleton7<MySingleton> { int _counter; public int Counter { get { return _counter; } } private MySingleton() { _counter = 0; } public void IncrementCounter() { //++_counter; //线程安全 Interlocked.Increment(ref _counter); } }
标签:
原文地址:http://www.cnblogs.com/laixiancai/p/4721675.html