A behavioural design pattern that breaks up a large algorithm into simple, abstract steps, which subclasses can either implement or override, based on how they work. In essence, it solves the problem of separating polymorphic algorithms from a detailed design through inheritance in classes (making it a compiled pattern).
Usecase
- When you have a polymorphic/generic algorithm, and you want to ensure that it is easily extensible while keeping its core functionality
- When you have a very large algorithm that needs to be split up into simple steps.
- When multiple specialised versions of a base algorithm need to be created.
Properties
- Abstract Base Algorithm: The base algorithm, which is a superclass for all specialised versions.
- One template method: This is essentially the main method that calls all the other steps defined in the algorithm. In most cases it would be marked as final, as subclasses should not modify it
- Multiple primitive operations (steps): These are the various essential steps of the algorithm, which the template method calls when the algorithm is run. It’s best to let these be protected.
- They can be abstract if they must be implemented.
- Or simple concrete method which can be overridden.
- Concrete Specialised Algorithm: A subclass of the base algorithm which overrides or implements certain primitive operations.
UML Class
classDiagram
direction TB
class BaseAlgorithm ~abstract~ {
+templateMethod() ~final~
#step1()
#step2()
#step3()*
}
class AlgorithmA {
#step3()
}
class AlgorithmB {
#step1()
#step2()
#step3()
}
BaseAlgorithm <|-- AlgorithmA
BaseAlgorithm <|-- AlgorithmB
templateMethod()
: The template method ofBaseAlgorithm
, which callsstep1...3()
. It should be markedfinal
to preventAlgorithmA
andAlgorithmB
from overriding it.step1(), step2()
: Concrete primitive operations, which can be overridden (as seen inAlgorithmB
), but don’t need to be.step3()
: An abstract primitive operation, which must be implemented by all subclasses.
Pros vs Cons
Pros
- Reduces duplicate, redundant code that is shared between specialised classes.
- Promotes Abstraction, as the template method doesn’t care how the subclasses implement it’s steps, as long as they work.
Cons
- Promotes strong coupling between the base class and it’s subclasses
- Not everything is flexible…#tosee
Example
Sorting Algorithm#todo