Template Pattern

Template is a behavioral pattern which uses abstract class, abstract class exposes defined way(s)/template(s) to execute its methods. Its subclasses can override the method implementation as per need but the invocation is to be in the same way as defined by an abstract class.

The example that demonstrates using of Template pattern contains Game abstract class defining operations with a template method set to be final so that it cannot be overridden. Cricket and Football are concrete classes that extend Game and override its methods. TemplatePatternDemo will use the Game to demonstrate use of template pattern.

Template Pattern UML Diagram

Step 1 : Create an abstract class with a template method being final

public abstract class Game {
protected abstract void initialize();
protected abstract void startPlay();
protected abstract void endPlay();

// template method
protected final void play() {
initialize();
startPlay();
endPlay();
}
}

Step 2 : Create concrete classes extending the above class

public class Cricket extends Game {
@Override
protected void initialize() {
System.out.println("Cricket Game Initialized! Start playing.");
}

@Override
protected void startPlay() {
System.out.println("Cricket Game Started. Enjoy the game!");
}

@Override
protected void endPlay() {
System.out.println("Cricket Game Finished!");
}
}

public class Football extends Game {
@Override
protected void initialize() {
System.out.println("Football Game Initialized! Start playing.");
}

@Override
protected void startPlay() {
System.out.println("Football Game Started. Enjoy the game!");
}

@Override
protected void endPlay() {
System.out.println("Football Game Finished!");
}
}

Step 3 : Use the Game’s template method play() to demonstrate a defined method of playing game

public class TemplatePatternDemo {
public static void main(String[] args) {
Game game = new Cricket();
game.play();

System.out.println();

game = new Football();
game.play();
}
}

The output will be :

Cricket Game Initialized! Start playing.
Cricket Game Started. Enjoy the game!
Cricket Game Finished!

Football Game Initialized! Start playing.
Football Game Started. Enjoy the game!
Football Game Finished!

Leave a Reply

Your email address will not be published. Required fields are marked *