IcsFromERPJob
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

143 lines
5.3 KiB

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