Template Method
The Template Method pattern can be used in situations where there is an algorithm or procedure, some steps of which could be implemented in multiple different ways. This pattern suggests defining the skeleton of an algorithm in one method, deferring some steps to subclasses. Template Method lets subclasses re-define certain steps of an algorithm without changing the algorithm's structure.
The outline of the algorithm can be kept in a method called Template Method in a class called Template Class, leaving out the specific implementations of the variant portions. Template Class can be a concrete or abstract class. The variant methods can even have default implementations. Interested classes can inherit the Template Class.
public abstract class TemplateClass { public final void calculateCarPrice() { // The algorithm = Template Method calculatePartsPrice(); calculateTaxPrice(); calculateInsurace(); } public abstract void calculatePartsPrice(); // They can even have some default implementations public abstract void calculateTaxPrice(); public abstract void calculateInsurace(); } ... public class TruckCalculator extends TemplateClass{ //give implementation for abstract methods. }
page revision: 4, last edited: 19 May 2010 11:54