Created
September 4, 2014 08:16
-
-
Save jjokela/e3e3fd30dea0cc1374a8 to your computer and use it in GitHub Desktop.
Factory: load types by using reflection
This file contains 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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Reflection; | |
using System.Text; | |
namespace WidgetApp | |
{ | |
/// <summary> | |
/// Simple factory that creates a widget based on its name | |
/// </summary> | |
public class WidgetFactory | |
{ | |
private Dictionary<string, Type> widgets; | |
/// <summary> | |
/// Load widget types available | |
/// </summary> | |
public WidgetFactory() | |
{ | |
LoadTypesICanRun(); | |
} | |
/// <summary> | |
/// Creates a new widget instance | |
/// </summary> | |
/// <param name="widgetName">Widget name</param> | |
/// <returns>Widget</returns> | |
public IWidget CreateInstance(string widgetName) | |
{ | |
IWidget widgetToReturn; | |
Type t = GetTypeToCreate(widgetName); | |
if (t == null) | |
throw new ArgumentException("No widget found!"); | |
else | |
widgetToReturn = Activator.CreateInstance(t) as IWidget; | |
return widgetToReturn; | |
} | |
/// <summary> | |
/// Checks if widget Type exists and returns it | |
/// </summary> | |
/// <param name="widgetName">Widget name</param> | |
/// <returns>Widget Type</returns> | |
private Type GetTypeToCreate(string widgetName) | |
{ | |
Type widgetType = null; | |
foreach (var widget in widgets) | |
{ | |
if (widget.Key.Contains(widgetName.ToLower())) | |
{ | |
widgetType = widgets[widget.Key]; | |
break; | |
} | |
} | |
return widgetType; | |
} | |
/// <summary> | |
/// Loads all IWidget types from this assembly | |
/// </summary> | |
private void LoadTypesICanRun() | |
{ | |
widgets = new Dictionary<string, Type>(); | |
Type[] typesInThisAssembly = Assembly.GetExecutingAssembly().GetTypes(); | |
foreach (Type t in typesInThisAssembly) | |
{ | |
if (t.GetInterface(typeof(IWidget).ToString()) != null) | |
widgets.Add(t.Name.ToLower(), t); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment