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. }
}
No comments:
Post a Comment