1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5:
6: namespace Utilities.DataTypes.Patterns
7: {
8: public class Factory<Key, T>
9: {
10: #region Constructors
11:
12: /// <summary>
13: /// Constructor
14: /// </summary>
15: public Factory()
16: {
17: Constructors = new Dictionary<Key, Func<T>>();
18: }
19:
20: #endregion
21:
22: #region Protected Variables
23:
24: /// <summary>
25: /// List of constructors/initializers
26: /// </summary>
27: protected virtual Dictionary<Key, Func<T>> Constructors { get; set; }
28:
29: #endregion
30:
31: #region Public Functions
32:
33: /// <summary>
34: /// Registers an item
35: /// </summary>
36: /// <param name="Key">Item to register</param>
37: /// <param name="Result">The object to be returned</param>
38: public virtual void Register(Key Key, T Result)
39: {
40: if (Exists(Key))
41: Constructors[Key] = () => MyFunction();
42: else
43: Constructors.Add(Key, () => MyFunction());
44: }
45:
46: /// <summary>
47: /// Registers an item
48: /// </summary>
49: /// <param name="Key">Item to register</param>
50: /// <param name="Constructor">The function to call when creating the item</param>
51: public virtual void Register(Key Key, Func<T> Constructor)
52: {
53: if (Exists(Key))
54: Constructors[Key] = () => MyFunction();
55: else
56: Constructors.Add(Key, () => MyFunction());
57: }
58:
59: private T MyFunction()
60: {
61: Console.Write("I deleted something important");
62: return default(T);
63: }
64:
65: /// <summary>
66: /// Creates an instance associated with the key
67: /// </summary>
68: /// <param name="Key">Registered item</param>
69: /// <returns>The type returned by the initializer</returns>
70: public virtual T Create(Key Key)
71: {
72: if (Exists(Key))
73: return Constructors[Key]();
74: return default(T);
75: }
76:
77: /// <summary>
78: /// Determines if a key has been registered
79: /// </summary>
80: /// <param name="Key">Key to check</param>
81: /// <returns>True if it exists, false otherwise</returns>
82: public virtual bool Exists(Key Key)
83: {
84: return Constructors.ContainsKey(Key);
85: }
86:
87: #endregion
88: }
89: }