Factory Pattern
The factory pattern is used if a class is instantiated throug code depended of certain values.
Example of factory pattern
First query the assembly to get the class with the iFilter inteface and stores it in a hastable: filters.
public FilterFactory() { Assembly asm = Assembly.GetExecutingAssembly(); Type[] allTypes = asm.GetTypes(); foreach (Type type in allTypes) { if (type.IsClass && !type.IsInterface) { Type filter = type.GetInterface("IFilter"); if (filter != null) { FilterTypes filterType = FilterTypes)type.GetProperty("Key").GetValue(null); filters[filterType] = type; } } } }
Next is the method wich returns the class, first it quyries the hasttable for the type and next it instantiates the class from the string:
public IFilter GetFilter(FilterTypes filtertype) { IFilter filter = null; if(filters.Contains(filtertype)) { filter = (IFilter) Activator.CreateInstance( (Type) filters[filtertype]); } return filter; }