


Definition: The Template Method pattern defines the skeleton of an algorithm in a method, deferring some or all steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
Template Method is much like Strategy, but not identical. Strategy allows you to hot-swap algorithms by storing an object that executes the algorithm. Template Method allows you to redefine different parts of algorithms for different subclasses.
Usage: Template Method is used when an interface contains a method that must be implemented differently by subclasses. However, the algorithm in this method has several steps that always must be performed in a certain order. Instead of overriding the whole method, create helper methods for each step. It is these helper methods that must be overridden by subclasses, rather than the whole method.
abstract class Algorithm {
doAlgorithm() {
doStep1();
doStep2();
doStep3();
}
abstract doStep1();
abstract doStep2();
abstract doStep3();
}
class MyAlgorithm extends Algorithm {
doStep1() {
//do work
}
doStep2() {
//do work
}
doStep3() {
//do work
}
}
Sadly, this example is contrived as it comes. It's more of a general template than an actual example.
Copyright (C) 2008-2009 Steven Fletcher. All rights reserved.