Skip to content

Instantly share code, notes, and snippets.

@paveltimofeev
Created July 5, 2011 06:00
Show Gist options
  • Save paveltimofeev/1064317 to your computer and use it in GitHub Desktop.
Save paveltimofeev/1064317 to your computer and use it in GitHub Desktop.
Generic FactoryMethod Pattern
/* Одним из недостатков шаблона 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
{
///...
}
@paveltimofeev
Copy link
Author

... для любого Product'а имеющего пустой конструктор по умолчанию... что-то в общем тут не так

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