Last active
August 29, 2015 14:00
-
-
Save Oobert/8ae57877ceebb35a4b89 to your computer and use it in GitHub Desktop.
C# simple object factory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You left out the letter "i" in "interface" (in the comments). Sorry but I have to fail this code review.