|
using System;
|
using System.Collections.Generic;
|
|
namespace HH.WMS.Utils
|
{
|
/// <summary>
|
/// 创建实例工厂
|
/// </summary>
|
public static class ObjectCreator
|
{
|
/// <summary>
|
/// 创建实例
|
/// </summary>
|
/// <typeparam name="T">指定要创建的实例类型</typeparam>
|
/// <returns>实例</returns>
|
public static T Create<T>()
|
where T : new()
|
{
|
return Create<T>(null);
|
}
|
|
/// <summary>
|
/// 创建实例
|
/// </summary>
|
/// <typeparam name="T">指定要创建的实例类型</typeparam>
|
/// <param name="initial">初始化实例</param>
|
/// <returns>实例</returns>
|
public static T Create<T>(Action<T> initial)
|
where T : new()
|
{
|
T t = new T();
|
if (initial != null)
|
{
|
initial(t);
|
}
|
return t;
|
}
|
|
/// <summary>
|
///
|
/// </summary>
|
/// <param name="t">Specify the type you want to create</param>
|
/// <param name="parameters"></param>
|
/// <returns></returns>
|
public static object Create(Type t, params object[] parameters)
|
{
|
return Activator.CreateInstance(t, parameters);
|
}
|
|
private static Dictionary<Type, object> cacheSingletons = new Dictionary<Type, object>();
|
private static object lockObj = new object();
|
|
/// <summary>
|
/// 创建单例
|
/// </summary>
|
/// <typeparam name="T">创建单例对象的类型</typeparam>
|
/// <returns></returns>
|
public static T CreateSingleton<T>()
|
where T : class, new()
|
{
|
object instance = null;
|
|
if (!cacheSingletons.TryGetValue(typeof(T), out instance))
|
{
|
lock (lockObj)
|
{
|
if (!cacheSingletons.TryGetValue(typeof(T), out instance))
|
{
|
instance = new T();
|
cacheSingletons.Add(typeof(T), instance);
|
}
|
}
|
}
|
return instance as T;
|
}
|
}
|
}
|