Friday, August 7, 2009

Template method pattern

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

Template method pattern in pdf

Template method pattern

Java Design Patterns At a Glance

---------------------------------------------------------
Usage

The template method is used to:

* let subclasses implement (through method overriding) 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 Java example:

Example

/**
* 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 {

protected 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() {
// Initialize money
}

void makePlay(int player) {
// Process one turn of player
}

boolean endOfGame() {
// Return true of 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() {
// 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. */

// ...

}
-----------------
class TestClient{

psvm()
{
Game obj=new Chess();
int playersCount=5;
obj.playOneGame(playersCoun);
}
}

No comments: