Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Template method pattern

From Wikipedia, the free encyclopedia
Behavioral design pattern in object-oriented programming
Not to be confused withTemplate processor.
This article includes a list ofgeneral references, butit lacks sufficient correspondinginline citations. Please help toimprove this article byintroducing more precise citations.(March 2012) (Learn how and when to remove this message)

Inobject-oriented programming, thetemplate method is one of thebehavioraldesign patterns identified by Gamma et al.[1] in the bookDesign 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 additionalhelper methods in the same class as thetemplate method.

Thehelper methods may be eitherabstract methods, in which case subclasses are required to provide concrete implementations, orhook methods, which have empty bodies in the superclass.Subclasses can (but are not required to) customize the operation byoverriding 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.[2]

Overview

[edit]

This pattern has two main parts:

  • The "template method" is implemented as a method in abase class (usually anabstract 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.[1] In the template method, portions of the algorithm that mayvary are implemented by sending self messages that request the execution of additionalhelper 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.[3] It is important that subclasses donot override thetemplate 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 ofinversion of control 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 tohook 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 algorithmwithout the need to override the template method itself. In other words, they provide a "hook" on which to "hang" variant implementations.

Structure

[edit]

UML class diagram

[edit]
A sample UML class diagram for the Template Method design pattern.[4]

In the aboveUMLclass diagram, theAbstractClass defines atemplateMethod() operation that defines the skeleton (template) of a behavior by

  • implementing the invariant parts of the behavior and
  • sending toself the messagesprimitive1() andprimitive2() , which, because they are implemented inSubClass1 , allow that subclass to provide a variant implementation of those parts of the algorithm.
Template Method inLePUS3.[5]

Usage

[edit]

Thetemplate 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 ofinversion of control. The template method is used for the following reasons.[3]

  • It lets subclasses implement varying behavior (throughoverriding of the hook methods).[6]
  • 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.[6]
  • 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,[6] and the overall workflow is left intact.

Use with code generators

[edit]
This section'stone or style may not reflect theencyclopedic tone used on Wikipedia. See Wikipedia'sguide to writing better articles for suggestions.(November 2025) (Learn how and when to remove this message)

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 thegeneration gap pattern.[7]

C++ example

[edit]

This C++23 implementation is based on the pre C++98 implementation in the book.

Cpp template method pattern UML.svg

importstd;usingstd::unique_ptr;// abstract classclassView{private:voidsetFocus(){std::println("View::setFocus called");}voidresetFocus(){std::println("View::resetFocus called");}public:// defines abstract primitive operations that concrete subclasses define to implement steps of an algorithm.virtualvoiddoDisplay()=0;// 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.voiddisplay(){setFocus();doDisplay();resetFocus();}virtual~View()=default;};// concrete classclassMyView:publicView{public:// implements the primitive operations to carry out subclass-specific steps of the algorithm.voiddoDisplay()override{// render the view's contentsstd::println("MyView::doDisplay called");}};intmain(intargc,char*argv[]){unique_ptr<View>myview=std::make_unique<MyView>();myview->display();}

The program output is

View::setFocuscalledMyView::doDisplaycalledView::resetFocuscalled

See also

[edit]

References

[edit]
  1. ^abGamma, Erich;Helm, Richard;Johnson, Ralph;Vlissides, John (1994). "Template Method".Design Patterns. Addison-Wesley. pp. 325–330.ISBN 0-201-63361-2.
  2. ^Freeman, Eric; Freeman, Elisabeth; Sierra, Kathy; Bates, Bert (2004). Hendrickson, Mike; Loukides, Mike (eds.).Head First Design Patterns(paperback). Vol. 1. O'REILLY. pp. 289, 311.ISBN 978-0-596-00712-6. Retrieved2012-09-12.
  3. ^ab"Template Method Design Pattern". Source Making - teaching IT professional. Retrieved2012-09-12.Template Method is used prominently in frameworks.
  4. ^"The Template Method design pattern - Structure".w3sDesign.com. Retrieved2017-08-12.
  5. ^LePUS3 legend. Retrieved fromhttp://lepus.org.uk/ref/legend/legend.xml.
  6. ^abcChung, Carlo (2011).Pro Objective-C Design Patterns for iOS. Berkeley, CA: Apress. p. 266.ISBN 978-1-4302-3331-2.
  7. ^Vlissides, John (1998-06-22).Pattern Hatching: Design Patterns Applied. Addison-Wesley Professional. pp. 85–101.ISBN 978-0201432930.

External links

[edit]
The WikibookComputer Science Design Patterns has a page on the topic of:Template method
Gang of Four
patterns
Creational
Structural
Behavioral
Concurrency
patterns
Architectural
patterns
Other
patterns
Books
People
Communities
See also
Retrieved from "https://en.wikipedia.org/w/index.php?title=Template_method_pattern&oldid=1324535917"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2026 Movatter.jp