Saturday, September 01, 2007

Letting generics in with Template Method pattern

Maybe it sounds silly but I just discovered a way to allow generics fit naturally into the Factory code. Paired development has its own benefits - I constantly overlooked this trick before and as a result was forced to get rid of some neat (from my point of view) generics designs.

Imagine you have started with this kind of design (I had to remember my first experiment so I apologize if the code seems a little but rough):

public abstract class AbstractResult<T>
{
public T Value
{
get {return _value;}
set {_value=value;}
}

public abstract string RenderResult();

public static AbstractResult<T> ResultFactory() {...}
}

public class CarResult : AbstractResult<Car>
{
public override string RenderResult()
{
//life sucks
Value.Render()
}
}

Unless you put some constraints on the generic type, you can't nicely use Value property inside your child class' Render method:

public abstract class AbstractResult<T>  where T : Vehicle 

It is still may not be a bad way out but something tells me that it is unnecessary limitation. Let's rebuild our classes slightly with the Template Method pattern:

public abstract class AbstractResult<T>
{
public T Value
{
get {return _value;}
set {_value=value;}
}

public virtual string RenderResult()
{
return ConcreteRenderResult();
}

public abstract string ConcreteRenderResult();

public static AbstractResult<T> ResultFactory() {...}
}

public class CarResult : AbstractResult<Car>
{
public override string ConcreteRenderResult()
{
//... do whatever
Value.Render();
}
}

With this implementation you have much more flexibility for child classes as well as for the factory method itself.

No comments:


© 2008-2013 Michael Goldobin. All rights reserved