using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace ICS.Common.DesignPattern { /// /// 单例模式 /// public static class Singleton where T : class, new() { // 定义一个静态变量来保存类的实例 private static T uniqueInstance; // 定义一个标识确保线程同步 private static object locker = null; // 定义私有构造函数,使外界不能创建该类实例 static Singleton() { locker = new object(); } /// /// 定义公有方法提供一个全局访问点,同时你也可以定义公有属性来提供全局访问点 /// /// public static T GetInstance() { // 当第一个线程运行到这里时,此时会对locker对象 "加锁", // 当第二个线程运行该方法时,首先检测到locker对象为"加锁"状态,该线程就会挂起等待第一个线程解锁 // lock语句运行完之后(即线程运行完之后)会对该对象"解锁" // 双重锁定只需要一句判断就可以了 if (uniqueInstance == null) { lock (locker) { // 如果类的实例不存在则创建,否则直接返回 if (uniqueInstance == null) { try { // uniqueInstance = Activator.CreateInstance(); ConstructorInfo constructorInfo = null; try { constructorInfo = typeof(T).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, new Type[0], null); } catch (Exception ex) { throw new InvalidOperationException(ex.Message, ex); } if (constructorInfo == null || constructorInfo.IsAssembly) { throw new InvalidOperationException($"在'{typeof(T).Name}'里面没有找到private或者protected的构造函数。"); } uniqueInstance = (T)constructorInfo.Invoke(null); } catch (Exception) { throw; } } } } return uniqueInstance; } public static T GetInstance(object[] para) { // 当第一个线程运行到这里时,此时会对locker对象 "加锁", // 当第二个线程运行该方法时,首先检测到locker对象为"加锁"状态,该线程就会挂起等待第一个线程解锁 // lock语句运行完之后(即线程运行完之后)会对该对象"解锁" // 双重锁定只需要一句判断就可以了 if (uniqueInstance == null) { lock (locker) { // 如果类的实例不存在则创建,否则直接返回 if (uniqueInstance == null) { try { // uniqueInstance = Activator.CreateInstance(); ConstructorInfo constructorInfo = null; try { constructorInfo = typeof(T).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, new Type[1] { para[0].GetType() }, null); } catch (Exception ex) { throw new InvalidOperationException(ex.Message, ex); } if (constructorInfo == null || constructorInfo.IsAssembly) { throw new InvalidOperationException($"在'{typeof(T).Name}'里面没有找到private或者protected的构造函数。"); } uniqueInstance = (T)constructorInfo.Invoke(para); } catch (Exception) { throw; } } } } return uniqueInstance; } } /// /// /// public sealed class Singleton4 where T : class,new () { private static readonly Singleton4 instance = new Singleton4(); /// /// 显式的静态构造函数用来告诉C#编译器在其内容实例化之前不要标记其类型 /// static Singleton4() { } private Singleton4() { } public static Singleton4 Instance { get { return instance; } } } }