World Library  
Flag as Inappropriate
Email this Article

Template method pattern

Article Id: WHEBN0000164866
Reproduction Date:

Title: Template method pattern  
Author: World Heritage Encyclopedia
Language: English
Subject:
Collection:
Publisher: World Heritage Encyclopedia
Publication
Date:
 

Template method pattern

In software engineering, the template method pattern is a behavioral design pattern that defines the program skeleton of an algorithm in a method, called template method, which defers some steps to subclasses.[1] It lets one redefine certain steps of an algorithm without changing the algorithm's structure.[2] This use of "template" is unrelated to C++ templates.

Contents

  • Introduction 1
  • Structure 2
  • Usage 3
  • Example in Java 4
  • Example in Swift 5
  • See also 6
  • References 7
  • External links 8

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.

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 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.[3] 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, 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 pattern may be used to add immediate present value to the software or with a vision to enhancements in the future. It is strongly related to the Non-Virtual Interface (NVI) pattern.

The Template Method pattern implements the Protected Variations GRASP principle, like the Adapter pattern does. The difference is that Adapter gives the same interface for several operations, while Template Method does so only for one.

Structure

Template method: UML class diagram.
Template Method in LePUS3 (legend)

Usage

The template method is used in frameworks, where each implements the invariant parts of a domain's architecture, leaving "placeholders" for customisation options. This is an example of inversion of control. Reasons to use the template method are to:[4]

  • Let subclasses implement (through method overriding) behavior that can vary.
  • Avoid duplication in the code: the general workflow structure is implemented once in the abstract class's algorithm, and necessary variations are implemented in each of the subclasses.
  • Control at what point(s) 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.


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 {
 /* Hook methods. Concrete implementation may differ in each subclass*/
    protected int playersCount;
    abstract void initializeGame();
    abstract void makePlay(int player);
    abstract boolean endOfGame();
    abstract void printWinner();

    /* A template method : */
    public 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() {
        // Initialize players
        // Initialize money
    }
    void makePlay(int player) {
        // Process one turn of player
    }
    boolean endOfGame() {
        // Return true if game is over 
        // according to Monopoly rules
    }
    void printWinner() {
        // Display who won
    }
    /* Specific declarations for the Monopoly game. */

    // ...
}

class Chess extends Game {

    /* Implementation of necessary concrete methods */
    void initializeGame() {
        // Initialize players
        // Put the pieces on the board
    }
    void makePlay(int player) {
        // Process a turn for the player
    }
    boolean endOfGame() {
        // Return true if in Checkmate or 
        // Stalemate has been reached
    }
    void printWinner() {
        // Display the winning player
    }
    /* Specific declarations for the chess game. */

    // ...
}

Example in Swift

import Foundation

protocol Game {
    var playersCount: Int { get set }
    func initializeGame()
    func makePlay()
    func endOfGame() -> Bool
    func printWinner()
}

class Monopoly: Game {
    var playersCount: Int
    private var gameEnded: Bool = false
    
    init(playersCount: Int) {
        self.playersCount = playersCount
    }
    
    func initializeGame() {
        println("Initialize \(playersCount) players.")
        println("Initialize money.")
    }
    
    func makePlay() {
        println("Process one turn of Monopoly player.")
    }
    
    func endOfGame() -> Bool {
        println("According to Monopoly rules, is game over? \(gameEnded)")
        return gameEnded
    }
    
    func printWinner() {
        println("Display who won the Monopoly.")
    }

     /* Specific declarations for the Monopoly game. */
}

class Chess: Game {
    private var gameEnded: Bool = false
    
    init() {
    }
    
    func initializeGame() {
        println("Initialize 2 players.")
        println("Put the pieces on the board.")
    }
    
    func makePlay() {
        println("Process one turn of Chess player.")
    }
    
    func endOfGame() -> Bool {
        println("Has Checkmate or Stalemate been reached? \(gameEnded)")
        return gameEnded
    }
    
    func printWinner() {
        println("Display who won the Chess.")
    }

    /* Specific declarations for the chess game. */
}

See also

References

  1. ^  
  2. ^ Freeman, Eric; Freeman, Elisabeth; Kathy, Sierra; Bert, Bates (2004). Hendrickson, Mike; Loukides, Mike, eds. "Head First Design Patterns" (paperback) 1. O'REILLY. p. 289.  
  3. ^ Freeman, Eric; Freeman, Elisabeth; Kathy, Sierra; Bert, Bates (2004). Hendrickson, Mike; Loukides, Mike, eds. "Head First Design Patterns" (paperback) 1. O'REILLY. p. 311.  
  4. ^ "Template Method Design Pattern". Source Making - teaching IT professional. Retrieved 2012-09-12. Template Method is used prominently in frameworks. 

External links

  • Working with Template Classes in PHP 5
  • Template method pattern in UML and in LePUS3 (a formal modelling language)
  • Difference between adapter and template method pattern
  • Template Method Design Pattern
  • Template Method Example
This article was sourced from Creative Commons Attribution-ShareAlike License; additional terms may apply. World Heritage Encyclopedia content is assembled from numerous content providers, Open Access Publishing, and in compliance with The Fair Access to Science and Technology Research Act (FASTR), Wikimedia Foundation, Inc., Public Library of Science, The Encyclopedia of Life, Open Book Publishers (OBP), PubMed, U.S. National Library of Medicine, National Center for Biotechnology Information, U.S. National Library of Medicine, National Institutes of Health (NIH), U.S. Department of Health & Human Services, and USA.gov, which sources content from all federal, state, local, tribal, and territorial government publication portals (.gov, .mil, .edu). Funding for USA.gov and content contributors is made possible from the U.S. Congress, E-Government Act of 2002.
 
Crowd sourced content that is contributed to World Heritage Encyclopedia is peer reviewed and edited by our editorial staff to ensure quality scholarly research articles.
 
By using this site, you agree to the Terms of Use and Privacy Policy. World Heritage Encyclopedia™ is a registered trademark of the World Public Library Association, a non-profit organization.
 


Copyright © World Library Foundation. All rights reserved. eBooks from Project Gutenberg are sponsored by the World Library Foundation,
a 501c(4) Member's Support Non-Profit Organization, and is NOT affiliated with any governmental agency or department.