1: public class Factory<Key,T>
2: {
3: #region Protected Variables
4:
5: /// <summary>
6: /// List of constructors/initializers
7: /// </summary>
8: protected Dictionary<Key, Func<T>> Constructors = new Dictionary<Key, Func<T>>();
9:
10: #endregion
11:
12: #region Public Functions
13:
14: /// <summary>
15: /// Registers an item
16: /// </summary>
17: /// <param name="Key">Item to register</param>
18: /// <param name="Result">The object to be returned</param>
19: public void Register(Key Key, T Result)
20: {
21: if (Constructors.ContainsKey(Key))
22: Constructors[Key] = new Func<T>(() => Result);
23: else
24: Constructors.Add(Key, new Func<T>(() => Result));
25: }
26:
27: /// <summary>
28: /// Registers an item
29: /// </summary>
30: /// <param name="Key">Item to register</param>
31: /// <param name="Constructor">The function to call when creating the item</param>
32: public void Register(Key Key, Func<T> Constructor)
33: {
34: if (Constructors.ContainsKey(Key))
35: Constructors[Key] = Constructor;
36: else
37: Constructors.Add(Key, Constructor);
38: }
39:
40: /// <summary>
41: /// Creates an instance associated with the key
42: /// </summary>
43: /// <param name="Key">Registered item</param>
44: /// <returns>The type returned by the initializer</returns>
45: public T Create(Key Key)
46: {
47: if (Constructors.ContainsKey(Key))
48: return Constructors[Key]();
49: return default(T);
50: }
51:
52: #endregion
53: }