In
object-oriented programming
Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of pr ...
, the template method is one of the
behavioral
Behavior (American English) or behaviour (British English) is the range of actions and mannerisms made by individuals, organisms, systems or artificial entities in some environment. These systems can include other systems or organisms as well ...
design patterns
''Design Patterns: Elements of Reusable Object-Oriented Software'' (1994) is a software engineering book describing software design patterns. The book was written by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, with a foreword ...
identified by Gamma et al.
in the book ''
Design Patterns
''Design Patterns: Elements of Reusable Object-Oriented Software'' (1994) is a software engineering book describing software design patterns. The book was written by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, with a foreword ...
''. The template method is a method in a superclass, usually an abstract superclass, and defines the skeleton of an operation in terms of a number of high-level steps. These steps are themselves implemented by additional ''helper methods'' in the same class as the ''template method''.
The ''helper methods'' may be either ''
abstract method
A method in object-oriented programming (OOP) is a procedure associated with a message and an object. An object consists of ''state data'' and ''behavior''; these compose an ''interface'', which specifies how the object may be utilized by any of ...
s'', in which case subclasses are required to provide concrete implementations, or ''
hook methods,'' which have empty bodies in the superclass.
Subclasses can (but are not required to) customize the operation by
overriding the hook methods. The intent of the template method is to define the overall structure of the operation, while allowing subclasses to refine, or redefine, certain steps.
Overview
This pattern has two main parts:
* The "template method" is implemented as a method in a
base class
In object-oriented programming, inheritance is the mechanism of basing an object or class upon another object ( prototype-based inheritance) or class ( class-based inheritance), retaining similar implementation. Also defined as deriving new classe ...
(usually an
abstract class
In programming languages, an abstract type is a type in a nominative type system that cannot be instantiated directly; a type that is not abstract – which ''can'' be instantiated – is called a ''concrete type''. Every instance of an abstra ...
). This method contains code for the parts of the overall algorithm that are invariant. The template ensures that the overarching algorithm is always followed.
In the template method, portions of the algorithm that may ''vary'' are implemented by sending self messages that request the execution of additional ''helper'' methods. In the base class, these helper methods are given a default implementation, or none at all (that is, they may be abstract methods).
* Subclasses of the base class "fill in" the empty or "variant" parts of the "template" with specific algorithms that vary from one subclass to another.
It is important that subclasses do ''not'' override the ''template method'' itself.
At run-time, the algorithm represented by the template method is executed by sending the template message to an instance of one of the concrete subclasses. Through inheritance, the template method in the base class starts to execute. When the template method sends a message to self requesting one of the helper methods, the message will be received by the concrete sub-instance. If the helper method has been overridden, the overriding implementation in the sub-instance will execute; if it has not been overridden, the inherited implementation in the base class will execute. This mechanism ensures that the overall algorithm follows the same steps every time, while allowing the details of some steps to depend on which instance received the original request to execute the algorithm.
This pattern is an example of
inversion of control
In software engineering, inversion of control (IoC) is a design pattern in which custom-written portions of a computer program receive the flow of control from a generic framework. A software architecture with this design inverts control as co ...
because the high-level code no longer determines what algorithms to run; a lower-level algorithm is instead selected at run-time.
Some of the self messages sent by the template method may be to ''hook methods.'' These methods are implemented in the same base class as the template method, but with empty bodies (i.e., they do nothing). Hook methods exist so that subclasses can override them, and can thus fine-tune the action of the algorithm ''without'' the need to override the template method itself. In other words, they provide a "hook" on which to "hang" variant implementations.
Structure
UML class diagram
In the above
UML
The Unified Modeling Language (UML) is a general-purpose, developmental modeling language in the field of software engineering that is intended to provide a standard way to visualize the design of a system.
The creation of UML was originally m ...
class diagram
In software engineering, a class diagram in the Unified Modeling Language (UML) is a type of static structure diagram that describes the structure of a system by showing the system's classes, their attributes, operations (or methods), and the rela ...
, the
AbstractClass
defines a
templateMethod()
operation that defines the skeleton (template) of a behavior by
* implementing the invariant parts of the behavior and
* sending to self the messages
primitive1()
and
primitive2()
, which, because they are implemented in
SubClass1
, allow that subclass to provide a variant implementation of those parts of the algorithm.
Usage
The ''template method'' is used in frameworks, where each implements the invariant parts of a domain's architecture, while providing hook methods for customization. This is an example of
inversion of control
In software engineering, inversion of control (IoC) is a design pattern in which custom-written portions of a computer program receive the flow of control from a generic framework. A software architecture with this design inverts control as co ...
. The template method is used for the following reasons.
* It lets subclasses implement varying behavior (through
overriding of the hook methods).
* It avoids duplication in the code: the general workflow of the algorithm is implemented once in the abstract class's template method, and necessary variations are implemented in the subclasses.
* It controls the point(s) at which specialization is permitted. If the subclasses were to simply override the template method, they could make radical and arbitrary changes to the workflow. In contrast, by overriding only the hook methods, only certain specific details of the workflow can be changed,
and the overall workflow is left intact.
Use with code generators
The template pattern is useful when working with auto-generated code. The challenge of working with generated code is that changes to the source code will lead to changes in the generated code; if hand-written modifications have been made to the generated code, these will be lost. How, then, should the generated code be customized?
The Template pattern provides a solution. If the generated code follows the template method pattern, the generated code will all be an abstract superclass. Provided that hand-written customizations are confined to a subclass, the code generator can be run again without risk of over-writing these modifications. When used with code generation, this pattern is sometimes referred to as the
generation gap pattern.
PHP example
abstract class Game
class Mario extends Game
class Tankfight extends Game
$game = new Tankfight();
$game->play();
$game = new Mario();
$game->play();
C++ example
#include
// abstract
class BaseClass ;
class ExtendedClass_one : public BaseClass ;
class ExtendedClass_two : public BaseClass ;
int main()
See also
*
Inheritance (computer science)
In object-oriented programming, inheritance is the mechanism of basing an object or class upon another object ( prototype-based inheritance) or class ( class-based inheritance), retaining similar implementation. Also defined as deriving new classe ...
*
Method overriding (programming)
Method overriding, in object-oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes. In addition t ...
*
GRASP (object-oriented designer)
*
Adapter pattern
In software engineering, the adapter pattern is a software design pattern (also known as wrapper, an alternative naming shared with the decorator pattern) that allows the interface of an existing class to be used as another interface. It is often ...
*
Strategy pattern
In computer programming, the strategy pattern (also known as the policy pattern) is a behavioral software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time in ...
References
External links
Six common uses of the template patternWorking with Template Classes in PHP 5Template Method Design Pattern
{{Design Patterns patterns
Software design patterns
Articles with example Java code
Method (computer programming)