Instructor: Stefan Mitsch
Template Method defines the skeleton of an algorithm, deferring some steps to subclasses
Problem illustration: algorithm structure duplicated over multiple classes
How to define algorithm structure once for all subclasses, while letting them adapt some steps?
Problem
Algorithm structure with some invariant steps and some changeable steps
Intent
Structure
The AbstractClass defines concrete invariant steps and abstract variant steps
AbstractClass
The AbstractClass defines a templateMethod that implements the algorithm structure by calling invariant and variant steps
templateMethod
The ConcreteClass implements the subclass-specific variant steps
ConcreteClass
final
// base class with template method public abstract class BaseEmailNotifier { // template method public final void send(Message m) { check(m.getRecipient()); check(m.getSubject()); doSend(m); } // steps mandatory to override protected abstract void doSend(Message m); // common steps private void check(Recipient r) { /* ... */ } private void check(Subject s) { /* ... */ } } // concrete algorithm variants public class GMailNotifier extends BaseEmailNotifier { protected void doSend(Message m) { /* ... */ } } public class ExchangeNotifier extends BaseEmailNotifier { protected void doSend(Message m) { /* ... */ } }
Code Smell: Two methods in subclasses perform similar steps in the same order, but some steps are different
Before: Algorithm duplicated in two subclasses
Template Method
Strategy