Template method pattern: Difference between revisions

Content deleted Content added
Vanderjoe (talk | contribs)
m Reverted 2 edits by 2403:4800:382D:CB27:AD8D:DA59:4B79:4C5 (talk) to last revision by Annh07
 
(67 intermediate revisions by 47 users not shown)
Line 1:
{{Short description|Behavioral design pattern in object-oriented programming}}
{{multiple issues|
{{distinguish|Template processor}}
{{more footnotes|date=March 2012}}
{{expert|date=May 2016}}
}}
In [[software engineering]], the '''template method pattern''' is a [[behavioral pattern|behavioral]] [[software design pattern|design pattern]] that defines the [[program skeleton]] of an [[algorithm]] in an operation, deferring some steps to [[Subclass (computer science)|subclass]]es.<ref name=":0">{{cite book
| last1 = Gamma
| first1 = Erich
| authorlink1 = Erich Gamma
| last2 = Helm
| first2 = Richard
| authorlink2 =Richard Helm
| last3 = Johnson
| first3 = Ralph
|authorlink3 =Ralph Johnson (computer scientist)
| last4 = Vlissides
| first4 = John
|authorlink4 =John Vlissides
| chapter = Template Method
| year = 1994
| title = [[Design Patterns]]
| pages =325–330
| publisher = Addison-Wesley
| isbn = 0-201-63361-2
}}</ref> It lets one redefine certain steps of an algorithm without changing the algorithm's structure.<ref name=":2">{{cite book|url=http://shop.oreilly.com/product/9780596007126.do|title=Head First Design Patterns|last2=Freeman|first2=Elisabeth|last3=Sierra|first3=Kathy|last4=Bates|first4=Bert|publisher=O'REILLY|year=2004|isbn=978-0-596-00712-6|editor-last=Hendrickson|editor-first=Mike|volume=1|___location=|page=289, 311|pages=|format=paperback|quote=|editor-last2=Loukides|editor-first2=Mike|via=|last1=Freeman|first1=Eric|accessdate=2012-09-12}}</ref>
 
In [[object-oriented programming]], the '''template method''' is one of the [[behavioral pattern|behavioral]] [[Software design pattern|design patterns]] identified by Gamma et al.<ref name=":0">{{cite book|title=Design Patterns|last1=Gamma|first1=Erich|last2=Helm|first2=Richard|last3=Johnson|first3=Ralph|last4=Vlissides|first4=John|publisher=Addison-Wesley|year=1994|isbn=0-201-63361-2|pages=[https://archive.org/details/designpatternsel00gamm/page/325 325–330]|chapter=Template Method|author-link1=Erich Gamma|author-link2=Richard Helm|author-link3=Ralph Johnson (computer scientist)|author-link4=John Vlissides|title-link=Design Patterns}}</ref> in the book ''[[Design Patterns]]''. 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''.
==Overview==
The Template Method
<ref name="GoF">{{cite book|author=Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides|title=Design Patterns: Elements of Reusable Object-Oriented Software|year=1994|publisher=Addison Wesley|isbn=0-201-63361-2|pages=325ff}}</ref>
design pattern is one of the twenty-three well-known
''[[Design Patterns|GoF design patterns]]''
that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.
 
The ''helper methods'' may be either ''[[abstract method]]s'', in which case subclasses are required to provide concrete implementations, or ''[[Hooking|hook methods]],'' which have empty bodies in the superclass. [[Subclass (computer science)|Subclass]]es can (but are not required to) customize the operation by [[Method overriding|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.<ref name=":2">{{cite book|url=http://shop.oreilly.com/product/9780596007126.do|title=Head First Design Patterns|last2=Freeman|first2=Elisabeth|last3=Sierra|first3=Kathy|last4=Bates|first4=Bert|publisher=O'REILLY|year=2004|isbn=978-0-596-00712-6|editor-last=Hendrickson|editor-first=Mike|volume=1|pages=289, 311|format=paperback|editor-last2=Loukides|editor-first2=Mike|last1=Freeman|first1=Eric|access-date=2012-09-12}}</ref>
<big>What problems can the Template Method design pattern solve?</big>
<ref>{{cite web|title=The Template Method design pattern - Problem, Solution, and Applicability|url=http://w3sdesign.com/?gr=b10&ugr=proble|website=w3sDesign.com|accessdate=2017-08-12}}</ref>
* The invariant parts of a behavior should be implemented only once so that subclasses can implement the variant parts.
* Subclasses should redefine only certain parts of a behavior without changing the other parts.
 
==Overview==
Usually, subclasses control how the behavior of a parent class is redefined, and they aren't restricted to redefine only certain parts of a behavior.
 
This pattern has two main parts:
<big>What solution does the Template Method design pattern describe?</big>
 
* The "template method" is implemented as a method in a [[base class]] (usually an [[abstract class]]). This method contains code for the parts of the overall algorithm that are invariant. The template ensures that the overarching algorithm is always followed.<ref name=":0" /> 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).
Define abstract operations (''primitives'') for the variant parts of a behavior.
* 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.<ref name=":1" /> It is important that subclasses do ''not'' override the ''template method'' itself.
<br>
Define a ''template method'' that
* implements the invariant parts of a behavior and
* calls abstract operations (''primitives'') that subclasses implement.
 
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.
The template method controls how subclasses redefine a behavior.
<br>
This is also referred to as ''inversion of control''
because subclasses do no longer control how the behavior of a parent class is redefined.
 
This pattern is an example of [[inversion of control]] because the high-level code no longer determines what algorithms to run; a lower-level algorithm is instead selected at run-time.
See also the UML class diagram below.
 
Some of the self-messages sent by the template method may be to ''[[Hooking|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.
==Introduction==
In the template method of this design pattern, one or more algorithm steps can be overridden by subclasses to allow differing behaviors while ensuring that the overarching algorithm is still followed.<ref name=":0" />
 
In object-oriented programming, a concrete class is created that provides the steps of an [[algorithm design]]. Steps that are considered invariant are implemented inside the base class. The steps that are considered to be variant, are given a default implementation or none at all. These variant steps must be supplied by concrete derived subclasses.<ref name=":1" /> Thus the general algorithm is saved in one place but the concrete steps may be changed by the subclasses.
 
The template method pattern thus manages the larger picture of task [[semantics]], and more refined implementation details of selection and sequence of methods. This larger picture calls abstract and non-abstract methods for the task at hand. The non-abstract methods are completely controlled by the template method, but the abstract methods, implemented in subclasses, provide the pattern's expressive power and degree of freedom. Template method's abstract class may also define hook methods that may be overridden by subclasses.<ref name=":2" />
 
Some or all of the abstract methods can be specialized in a subclass, allowing the writer of the subclass to provide particular behavior with minimal modifications to the larger semantics. The template method (that is non-abstract) remains unchanged in this pattern, ensuring that the subordinate non-abstract methods and abstract methods are called in the originally intended sequence.
 
The template method pattern occurs frequently, at least in its simplest case, where a method calls only one abstract method when using object oriented languages. If a software writer uses a [[Polymorphism in object-oriented programming|polymorphic]] method at all, this design pattern may be a rather natural consequence. This is because a method calling an abstract or polymorphic function is simply the reason for being of the abstract or polymorphic method. The template method pattern may be used to add immediate present value to the software or with a vision to enhancements in the future.
 
== Structure ==
=== UML class diagram ===
[[File:w3sDesign Template Method Design Pattern UML.jpg|frame|none|A sample UML class diagram for the Template Method design pattern. <ref>{{cite web|title=The Template Method design pattern - Structure |url=http://w3sdesign.com/?gr=b10&ugr=struct|website=w3sDesign.com|accessdateaccess-date=2017-08-12}}</ref>]]
 
In the above [[Unified Modeling Language|UML]] [[Class diagram|class diagram]], the <code>AbstractClass</code> defines a <code>templateMethod()</code> operation that defines the skeleton (template) of a behavior by
defines the skeleton (template) of a behavior by
* implementing the invariant parts of the behavior and
* callingsending to '''self''' the messages abstract <code>primitive1()</code> and <code>primitive2()</code> operations, towhich, deferbecause implementingthey theare variantimplemented parts toin <code>SubClass1</code> , allow that subclass to provide a variant implementation of those parts of the algorithm.<br>
 
=== Class diagram ===
[[Image:Template Method UML.svg|thumb|300px|none|Template method: [[Unified Modeling Language|UML]] [[class diagram]].]]
[[Image:Template Method pattern in LePUS3.gif|thumb|none|300px|Template Method in [[Lepus3|LePUS3]].<ref>LePUS3 legend. Retrieved from http://lepus.org.uk/ref/legend/legend.xml.</ref>]]
 
==Usage==
 
The ''template method'' is used in frameworks, where each implements the invariant parts of a ___domain's architecture, leavingwhile "placeholders"providing hook methods for customization options. This is an example of [[inversion of control]]. The template method is used for the following reasons:.<ref name=":1">{{cite web | url = http://sourcemaking.com/design_patterns/template_method | title = Template Method Design Pattern | publisher = Source Making - teaching IT professional | quote = Template Method is used prominently in frameworks. | access-date = 2012-09-12}}</ref>
* It lets subclasses implement varying behavior (through [[Method overriding (programming)|overriding]] of the hook methods).<ref name=":3">{{Cite book|title=Pro Objective-C Design Patterns for iOS|last=Chung|first=Carlo|publisher=Apress|year=2011|isbn=978-1-4302-3331-2|___location=Berkeley, CA|pages=266}}</ref>
| url = http://sourcemaking.com/design_patterns/template_method
* 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.<ref name=":3" />
| title = Template Method Design Pattern
* 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,<ref name=":3" /> and the overall workflow is left intact.
| publisher = Source Making - teaching IT professional
| quote = Template Method is used prominently in frameworks.
| accessdate = 2012-09-12
}}</ref>
* Let subclasses implement varying behavior (through [[Method overriding (programming)|method overriding]]).<ref name=":3">{{Cite book|title=Pro Objective-C Design Patterns for iOS|last=Chung|first=Carlo|publisher=Apress|year=2011|isbn=978-1-4302-3331-2|___location=Berkely, CA|pages=266|quote=|via=}}</ref>
* Avoid duplication in the code: the general workflow structure is implemented once in the abstract class's [[algorithm]], and necessary variations are implemented in the subclasses.<ref name=":3" />
* Control at what point(s) [[Inheritance (computer science)|subclassing]] is allowed. As opposed to a simple polymorphic override, where the base method would be entirely rewritten allowing radical change to the workflow, only the specific details of the workflow are allowed to change.<ref name=":3" />
 
=== UsageUse with code generators ===
The template pattern is useful when working with auto-generated code. The challenge of working with generated code is that anychanges refinement ofto the source materialcode will lead to changes in the generated code, which could; overwriteif hand-written modifications. Thishave maybeen bemade solved usingto the Template pattern, by generating abstractgenerated code, andthese making hand-written modifications to a concrete subclass or implementation class. The abstract code maywill be in the form of an abstract class in C++, or an interface in Java or C#lost. The hand-written code would go into a subclass in C++How, and an implementing class in Java or C#. When used with code generationthen, this pattern is sometimes referred to asshould the [[Generationgenerated gapcode (pattern)|Generationbe Gap]] pattern.<ref>{{cite book|last1=Vlissides|first1=John|title=Pattern Hatching: Design Patterns Applied|date=1998-06-22|publisher=Addison-Wesley Professional|isbn=978-0201432930|pages=85–101|url=http://www.informit.com/store/pattern-hatching-design-patterns-applied-9780201432930}}</ref>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)|generation gap pattern]].<ref>{{cite book|last1=Vlissides|first1=John|title=Pattern Hatching: Design Patterns Applied|date=1998-06-22|publisher=Addison-Wesley Professional|isbn=978-0201432930|pages=85–101|url=http://www.informit.com/store/pattern-hatching-design-patterns-applied-9780201432930}}</ref>
 
==C++ example==
This C++14 implementation is based on the pre C++98 implementation in the book.
 
[[File:Cpp template method pattern UML.svg|Cpp template method pattern UML.svg]]
 
<syntaxhighlight lang="c++">
#include <iostream>
#include <memory>
 
class View { // AbstractClass
public:
// defines abstract primitive operations that concrete subclasses define to implement steps of an algorithm.
virtual void doDisplay() {}
// implements a template method defining the skeleton of an algorithm. The template method calls primitive operations as well as operations defined in AbstractClass or those of other objects.
void display() {
setFocus();
doDisplay();
resetFocus();
}
virtual ~View() = default;
private:
void setFocus() {
std::cout << "View::setFocus\n";
}
void resetFocus() {
std::cout << "View::resetFocus\n";
}
};
 
class MyView : public View { // ConcreteClass
// implements the primitive operations to carry out subclass-specific steps of the algorithm.
void doDisplay() override {
// render the view's contents
std::cout << "MyView::doDisplay\n";
}
};
 
int main() {
// The smart pointers prevent memory leaks
std::unique_ptr<View> myview = std::make_unique<MyView>();
myview->display();
}
</syntaxhighlight>
 
The program output is
 
<syntaxhighlight lang="c++">
View::setFocus
MyView::doDisplay
View::resetFocus
</syntaxhighlight>
 
== See also ==
* [[Inheritance (computerobject-oriented scienceprogramming)]]
* [[Method overriding (programming)]]
* [[GRASP (object-oriented design)|GRASP (object-oriented designer)]]
* [[Adapter pattern]]
* [[Strategy pattern]]
 
== References ==
Line 103 ⟶ 105:
 
== External links ==
{{wikibooksWikibooks|Computer Science Design Patterns|Template method|Template-method implementations in various languages}}
* [httphttps://www.devshedcodeproject.com/cArticles/a307452/PHP/Workingcommon-withuse-of-Template-ClassesDesign-inpattern-PHPDesign-5/pat WorkingSix withcommon Templateuses Classesof inthe PHPtemplate 5pattern]
* [http://www.lepus.org.uk/ref/companion/TemplateMethod.xml Template method pattern in UML and in LePUS3] (a formal modelling language)
* [http://sourcemaking.com/design_patterns/template_method Template Method Design Pattern]
* [http://www.24bytes.com/2011/10/template-method.html Template Method Example]
{{Design Patterns Patterns}}
 
 
 
{{Design Patterns patterns}}
<!--Interwikies-->
 
<!--Categories-->
[[Category:Software design patterns]]
[[Category:Articles with example Java code]]