Skip to content

Instantly share code, notes, and snippets.

@Oobert
Last active August 29, 2015 14:00
Show Gist options
  • Save Oobert/8ae57877ceebb35a4b89 to your computer and use it in GitHub Desktop.
Save Oobert/8ae57877ceebb35a4b89 to your computer and use it in GitHub Desktop.
C# simple object factory
public static class Factory
{
private static Dictionary<Type, Object> _typeLookup = new Dictionary<Type, object>();
/// <summary>
/// Clears the dispener.
/// </summary>
public static void ClearDispener()
{
_typeLookup.Clear();
}
/// <summary>
/// Adds an object to be dispensed for the given type.
/// </summary>
/// <typeparam name="Interface">The type of the Interface.</typeparam>
/// <typeparam name="Class">The type of the Class.</typeparam>
/// <param name="obj">The obj.</param>
public static void DispenseForType<Interface, Class>(Interface obj)
{
if (_typeLookup.ContainsKey(typeof(Class)))
{
_typeLookup[typeof(Class)] = obj;
}
else
{
_typeLookup.Add(typeof(Class), obj);
}
}
/// <summary>
/// Creates the specified type passing in the supplied args.
/// </summary>
/// <typeparam name="Interface">The type of the interface.</typeparam>
/// <typeparam name="Class">The type of the class.</typeparam>
/// <param name="args">The constuctor arguments.</param>
/// <returns></returns>
public static Interface Create<Interface, Class>(params object[] args) where Class : Interface
{
if (_typeLookup.ContainsKey(typeof(Class)))
{
return (Interface)_typeLookup[typeof(Class)];
}
return (Interface)Activator.CreateInstance(typeof(Class), args);
}
/// <summary>
/// Create the specified type using default/no arg constuctor
/// </summary>
/// <typeparam name="Interface">The type of the interface</typeparam>
/// <typeparam name="Class">The type of the class</typeparam>
/// <returns></returns>
public static Interface Create<Interface, Class>() where Class : Interface, new()
{
if (_typeLookup.ContainsKey(typeof(Class)))
{
return (Interface)_typeLookup[typeof(Class)];
}
return (Interface)new Class();
}
}
@phillijw
Copy link

You left out the letter "i" in "interface" (in the comments). Sorry but I have to fail this code review.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment