.comment-link {margin-left:.6em;}

Friday, July 29, 2005

Template vs Strategy Patterns

The Template pattern is similar to the Strategy pattern. These two patterns differ in scope and in methodology.

Strategy is used to allow callers to vary an entire algorithm, like how to calculate different types of tax, while Template Method is used to vary steps in an algorithm. Because of this, Strategy is more coarsely grained. The Template allows finer-grained controls in the sequent of operations, and yet allows the implementations of these details to vary.

The other main difference is that Strategy uses delegation while Template Method uses inheritance. In Strategy, the algorithm is delegated to the another xxxStrategy class that the subject will have a reference to, but with Template you subclass the base and override methods to make changes.

Strategy pattern example:

Class MainSubject
{

ITaxStrategy taxCalculator = GetStrategy(taxType);
//strategy is member class.
taxCalculator.Calculate();

private GetStrategy(string taxType)
{

if (taxType == "incometax")
return new IncomeTaxStrategy();
else if (taxType == "propertytax")
return new PropertyTaxStrategy();
}
}

Class IncomeTaxStrategy : ITaxStrategy
{


public Calculate()
{
//calculate based on income tax rates.
}

}

Class PropertyTaxStrategy : ITaxStrategy
{

public Calculate()
{
//calculate based on property tax
policies.
}

}

Template pattern example:


abstract Class TaxCalculator
{
public CalculateTax()
{
CalculateIncome();
tax =+ CalculateTax();
tax =+ CalculateRelief();

}
abstract CalculateTax();
abstract CalculateRelief();

}

Class IncomeTaxCalculator : TaxCalculator
{

override CalculateTax() { //calculate income tax. }
override CalculateRelief() { //calculate personal relief }

}

Class PropertyTaxCalculator : TaxCalculator
{

override CalculateTax() { //calculate property tax. }
override CalculateRelief() { //do nothing; no relief. }

}

Comments:
Because of subclassing nature, the template pattern partially violates Dependancy Inversion Principle. Whereas Strategy pattern does not it perfectly adheres to DIP.
 
Great explanation and example, thanks very much !!. We were studing the two patterns and this answered all our questions.
Fabian
 
Post a Comment



<< Home