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.

In such scenarios, the Template Method pattern suggests keeping the outline of the algorithm in a separate method referred to as a Template Method inside a class, which may be referred to as a 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 call later 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: 3, last_edited: 1231123812|%e %b %Y, %H:%M %Z (%O ago)
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License