1
pulg
2025-05-14 5a640911f7e7ef3a003775993f077e1a0e9ac130
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
 
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;
        }
    }
}