The Template Method pattern provides a method that allows subclasses to override parts of the method without rewriting it. Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. The Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.
The following is a benefit of using the Template Method pattern:
- Fundamental technique for reusing code
You should use the Template Method pattern when:
- You want to implement the invariant parts of an algorithm once and use subclasses to implement the behavior that can vary.
- When common behavior among subclasses should be factored and localized in a common class to avoid code duplication.