Template method pattern


Template method pattern

[
LePUS3 ( [http://lepus.org.uk/ref/legend/legend.xml legend] ) ]

In software engineering, the template method pattern is a design pattern.It is a so-called behavioral pattern, and is unrelated to C++ templates.

Introduction

In a template pattern, the model (data such as XML, or a set of APIs) has no inherent knowledge of how it would be utilized. The actual algorithm is delegated to the views, i.e. templates. Different templates could be applied to the same set of data or APIs and produce different results. Thus, it is a subset of model-view-controller patterns without the controller. The pattern does not have to be limited to the object-oriented programming. For example, different XSLT templates could render the same XML data and produce different outputs. C++ templates also make it possible to code the algorithms (i.e. views) without having to use abstract classes or interfaces.

In object-oriented programming, first a class is created that provides the basic steps of an algorithm design. These steps are implemented using abstract methods. Later on, subclasses change the abstract methods to implement real actions. Thus the general algorithm is saved in one place but the concrete steps may be changed by the subclasses.

The template method 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. The expressive power and degrees of freedom occur in abstract methods that may be implemented in subclasses. Some or all of the abstract methods can be specialized in the subclass, the abstract method is the smallest unit of granularity, allowing the writer of the subclass to provide particular behavior with minimal modifications to the larger semantics. In contrast the template method need not be changed and is not an abstract operation and thus may guarantee required steps before and after the abstract operations. Thus the template method is invoked and as a consequence the subordinate non-abstract methods and abstract methods are called in the correct sequence.

The template method occurs frequently, at least in its simplest case, where a method calls only one abstract method, with object oriented languages. If a software writer uses a 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 may be used to add immediate present value to the software or with a vision to enhancements in the future.

The template method is strongly related to the NVI (Non-Virtual Interface) pattern. The NVI pattern recognizes the benefits of a non-abstract method invoking the subordinate abstract methods. This level of indirection allows for pre and post operations relative to the abstract operations both immediately and with future unforeseen changes. The NVI pattern can be deployed with very little software production and runtime cost. Many commercial frameworks employ the NVI pattern.

Usage

The template method is used to:
* let subclasses implement behaviour that can vary
* avoid duplication in the code: you look for the general code in the algorithm, and implement the variants in the subclasses
* control at what point(s) subclassing is allowed.

The control structure (inversion of control) that is the result of the application of a template pattern is often referred to as the Hollywood Principle: "Don't call us, we'll call you." Using this principle, the template method in a parent class controls the overall process by calling subclass methods as required. This is shown in the following example:

Example (in Java)

/** * An abstract class that is common to several games in * which players play against the others, but only one is * playing at a given time. */ abstract class Game { private int playersCount; abstract void initializeGame(); abstract void makePlay(int player); abstract boolean endOfGame(); abstract void printWinner(); /* A template method : */ final void playOneGame(int playersCount) { this.playersCount = playersCount; initializeGame(); int j = 0; while (!endOfGame()){ makePlay(j); j = (j + 1) % playersCount; } printWinner(); } }

//Now we can extend this class in order to implement actual games:

class Monopoly extends Game { /* Implementation of necessary concrete methods */ void initializeGame() { // ... } void makePlay(int player) { // ... } boolean endOfGame() { // ... } void printWinner() { // ... } /* Specific declarations for the Monopoly game. */ // ... }

class Chess extends Game { /* Implementation of necessary concrete methods */ void initializeGame() { // ... } void makePlay(int player) { // ... } boolean endOfGame() { // ... } void printWinner() { // ... } /* Specific declarations for the chess game. */ // ... }

Example (in C++)

In C++ it is not necessary to use inheritance and abstract (pure virtual) methods. For example, the Standard Library (STL) has been conceived using another paradigm: the templatization. Here is an example using the "traits" feature on which the STL relies.

/** * The use of traits class to implement the Template Method Pattern * Note: this method has been heavily used in the Standard Library, the example below is just a bit simpler */

"example.h"

template class example_traits { public: /** * Typedefs */ typedef T value; typedef const T const_value; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; /** * Methods */ static pointer Clone(const_pointer iClonee) { return new T(*iClonee); } // Clone }; // class example_traits

template > class example { public: /** * Typedefs */ typedef typename U::value value; typedef typename U::const_value const_value; typedef typename U::pointer pointer; typedef typename U::const_pointer const_pointer; typedef typename U::reference reference; typedef typename U::const_reference const_reference /** * Default constructors and such are not shown */ // We just add a constructor that takes a pointer to the object to initialize its attribute example(pointer object); // definition not shown /** * Methods */ example clone() {

// Some code to log that we clone the object

pointer aClone = U::Clone(object_); // actual cloning

// Some code to clean up the object or change its state if we want

return example(aClone); } // clone private: /** * object */ pointer object_; }; // example

"myClass.h"

class MyClass { public: MyClass* duplicateMe() const; // method to obtain a clone /** stuff **/ }; // MyClass

/** * Two different methods */

// specialization of the traits class template <> class example_traits { /** * Typedefs */ typedef MyClass value; typedef const MyClass const_value; typedef MyClass* pointer; typedef const MyClass* const_pointer; typedef MyClass& reference; typedef const MyClass& const_reference; /** * Methods */ static pointer Clone(const_pointer iClonee) { return iClonee->duplicateMe(); // This line is changed to use the clone method of MyClass } // Clone }; // example

// creation of a brand new class class MyClassExampleTraits { /** * Typedefs */ typedef MyClass value; typedef const MyClass const_value; typedef MyClass* pointer; typedef const MyClass* const_pointer; typedef MyClass& reference; typedef const MyClass& const_reference; /** * Methods */ static pointer Clone(const_pointer iClonee) { return iClonee->duplicateMe(); // This line is changed to use the clone method of MyClass } // Clone }; // MyClassExampleTraits

"main.cpp"

int main() { // Using the first method example aFirstExample; // the default parameter is set to example_traits which is our specialization example aFirstClone = aFirstExample->clone();

// using the first method, but precising the second parameter example > aSecondExample; aFirstClone = aSecondExample->clone(); // Note that the type of aFirstClone is compatible // in fact it is exactly the same type (we have just explicitely precised the argument)

// Using the second method example aThirdExample; // the traits class is a user defined one example aSecondClone = aThirdExample->clone();

return 0; } // main

External links

* [http://www.dofactory.com/Patterns/PatternTemplate.aspx Template design pattern in C# and VB.NET]
* [http://www.devshed.com/c/a/PHP/Working-with-Template-Classes-in-PHP-5/ Working with Template Classes in PHP 5]
* [http://www.lepus.org.uk/ref/companion/TemplateMethod.xml Template Method pattern in UML and in LePUS3] (a formal modelling language)


Wikimedia Foundation. 2010.

Look at other dictionaries:

  • Factory method pattern — Factory method in UML Facto …   Wikipedia

  • Method overriding — 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. The… …   Wikipedia

  • Template matching — is a technique in Digital image processing for finding small parts of an image which match a template image. It can be used in manufacturing as a part of quality control, [Aksoy, M. S., O. Torkul, and I. H. Cedimoglu. An industrial visual… …   Wikipedia

  • Template metaprogramming — is a metaprogramming technique in which templates are used by a compiler to generate temporary source code, which is merged by the compiler with the rest of the source code and then compiled. The output of these templates include compile time… …   Wikipedia

  • template — UK US /ˈtempleɪt/ noun [C] ► a method or system that can be copied and used by others: serve/act as a template (for sth) »The deal will act as a template for future negotiations. provide/create/become a template (for sth) »Transport for London… …   Financial and business terms

  • pattern — [n1] design, motif arrangement, decoration, device, diagram, figure, guide, impression, instruction, markings, mold, motive, original, ornament, patterning, plan, stencil, template, trim; concepts 259,625 Ant. plainness pattern [n2] arrangement,… …   New thesaurus

  • Pattern (disambiguation) — A pattern is a form, template, or model. Pattern can refer to: * Pattern (devotional), in Irish Catholicism, the devotional practices associated with a patron saint * Pattern theory, in mathematics * Airfield traffic pattern, the traffic flow… …   Wikipedia

  • pattern — Synonyms and related words: Geistesgeschichte, Hegelian idea, Kantian idea, Platonic form, Platonic idea, action, actions, activity, acts, address, aesthetic form, affectation, air, anatomy, antetype, antitype, archetype, architectonics,… …   Moby Thesaurus

  • pattern — I (New American Roget s College Thesaurus) n. form, original; mold, example; design, plan, last; model, ideal. See perfection, conformity, ornament. II (Roget s IV) n. 1. [A model] Syn. original, guide, model, exemplar; see model 1 , 2 . 2.… …   English dictionary for students

  • pattern — n 1. design, patterning, figure, motif, device; marking, etching, engraving, chasing; decoration, decorative scheme, ornamentation; configuration, figuration, delineation, outline, conformation, formation, composition, layout. 2. type, stripe,… …   A Note on the Style of the synonym finder


Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”

We are using cookies for the best presentation of our site. Continuing to use this site, you agree with this.