Skip to content

Instantly share code, notes, and snippets.

@forcewake
Created April 9, 2014 07:28
Show Gist options
  • Save forcewake/10235878 to your computer and use it in GitHub Desktop.
Save forcewake/10235878 to your computer and use it in GitHub Desktop.
Factory
public interface IFactory<in TKey, TValue>
{
/// <summary>
/// Registers an item
/// </summary>
/// <param name="key">Item to register</param>
/// <param name="value">The object to be returned</param>
void Register(TKey key, TValue value);
/// <summary>
/// Registers an item
/// </summary>
/// <param name="key">Item to register</param>
/// <param name="constructor">The function to call when creating the item</param>
void Register(TKey key, Func<TValue> constructor);
/// <summary>
/// Creates an instance associated with the key
/// </summary>
/// <param name="key">Registered item</param>
/// <returns>The type returned by the initializer</returns>
TValue Create(TKey key);
}
public class Factory<TKey, TValue> : IFactory<TKey, TValue>
{
#region Protected Variables
/// <summary>
/// List of constructors/initializers
/// </summary>
protected Dictionary<TKey, Func<TValue>> factory = new Dictionary<TKey, Func<TValue>>();
#endregion
#region Public Functions
/// <summary>
/// Registers an item
/// </summary>
/// <param name="key">Item to register</param>
/// <param name="value">The object to be returned</param>
public void Register(TKey key, TValue value)
{
if (factory.ContainsKey(key))
{
factory[key] = () => value;
}
else
{
factory.Add(key, () => value);
}
}
/// <summary>
/// Registers an item
/// </summary>
/// <param name="key">Item to register</param>
/// <param name="constructor">The function to call when creating the item</param>
public void Register(TKey key, Func<TValue> constructor)
{
if (factory.ContainsKey(key))
{
factory[key] = constructor;
}
else
{
factory.Add(key, constructor);
}
}
/// <summary>
/// Creates an instance associated with the key
/// </summary>
/// <param name="key">Registered item</param>
/// <returns>The type returned by the initializer</returns>
public TValue Create(TKey key)
{
if (factory.ContainsKey(key))
{
return factory[key]();
}
throw new KeyNotFoundException(string.Format("Key {0} was not found in the factory - check if it is correct", key));
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment