The Template Method design pattern provides a solution:
Define abstract operations
(primitives)
for the
variant parts of a behavior.
Define a template method
that
- implements the invariant parts of a behavior and
- calls primitives that subclasses implement.
Describing the Template Method design in more detail is
the theme of the following sections.
See Applicability section for all problems Template Method can solve.
[BGI]
-
The key idea in this pattern is to control subclassing.
Subclasses do no longer control
how the behavior of a parent class
is redefined.
Instead, a parent class controls how subclasses redefine it.
This is also referred to as inversion of control.
"This refers to how a parent class calls the operations of
a subclass and not the other way around."
[GoF, p327]
-
Inversion of control is a common feature
of
frameworks.
When using a library (reusable classes), we call the code
we want to reuse.
When using a framework (reusable application), we write
subclasses and implement the variant code the framework
calls.
-
Template methods are a fundamental technique for
code reuse
(1) to implement the common
(invariant) parts of a behavior once
"and leave it up to subclasses to implement the behavior that
can vary." [GoF, p326]
(2) and from a refactoring point of view, to
eliminate code duplication by factoring out
invariant behavior among classes
and
localizing (generalizing) it in a common class.
Background Information
-
The pattern calls abstract operations for variant parts
of a behavior primitives
because the template method composes primitive
operations to get a more complex operation.