Created
July 5, 2011 06:00
-
-
Save paveltimofeev/1064317 to your computer and use it in GitHub Desktop.
Generic FactoryMethod Pattern
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
/* Одним из недостатков шаблона FactoryMethod является необходимость создания отдельного Creator'а для каждого Product'а. | |
Данный подход позволяет использовать GenericCreator для создания любого Product'а.*/ | |
/// | |
/// This is base class (super class) for FactoryMethod | |
/// | |
internal abstract class FactoryMethodCreatorBase | |
{ | |
public abstract FactoryMethodProductBase FactoryMethod(); | |
public FactoryMethodProductBase TypeFactoryMethod(Type type) | |
{ | |
FactoryMethodProductBase obj; | |
if (type.IsSubclassOf(typeof(FactoryMethodProductBase))) | |
obj = (FactoryMethodProductBase)Activator.CreateInstance(type); | |
else | |
throw new InvalidCastException(type.FullName); | |
return obj; | |
} | |
public T FactoryMethod<T>() | |
where T : FactoryMethodProductBase, new() | |
{ | |
return new T(); | |
} | |
} | |
/// | |
/// This is generic Creator class | |
/// | |
internal class GenericCreator<T> : FactoryMethodCreatorBase | |
where T : FactoryMethodProductBase, new() | |
{ | |
public override FactoryMethodProductBase FactoryMethod() | |
{ | |
return new T(); | |
} | |
public T GenericFactoryMethod() | |
{ | |
return new T(); | |
} | |
} | |
/// | |
/// This is base class for concrete "product". | |
/// Any class derived from this could be initialized by means of GenericCreator<T>. | |
/// | |
internal abstract class FactoryMethodProductBase | |
{ | |
///... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
... для любого Product'а имеющего пустой конструктор по умолчанию... что-то в общем тут не так