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. It lets one redefine certain steps of an algorithm without changing the algorithm's structure.
According to the official Gang of Four (GoF) phrasing, the Template
Method will “Define the skeleton of an
algorithm in an operation, deferring some steps to subclasses. Template Method
lets subclasses redefine certain steps of an algorithm without changing the
algorithm’s structure.”
In Template pattern, an abstract class
exposes defined way(s)/template(s) to execute its methods. Its subclasses can
overrides the method implementations as per need basis but the invocation is to
be in the same way as defined by an abstract class. This pattern comes under
behavior pattern category.
Intent
1) Define the skeleton of an algorithm in an operation, deferring some steps to client subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
2) Base class declares algorithm 'placeholders', and derived classes implement the placeholders.
2) Base class declares algorithm 'placeholders', and derived classes implement the placeholders.
Problem
Two different components have significant similarities, but demonstrate no reuse of common interface or implementation. If a change common to both components becomes necessary, duplicate effort must be expended.
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 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.
If we take a look at the dictionary definition of a template we can see that a template is a preset format, used as a starting point for a particular application so that the format does not have to be recreated each time it is used. On the same idea is the template method is based. A template method defines an algorithm in a base class using abstract operations that subclasses override to provide concrete behavior so that means you should use the Template Method pattern when you have an algorithm that is made of up multiple steps and you want to be able to customize some of those steps.
Note that if you want to rewrite everything from scratch every time — if every step has to be customized by writing it from scratch — then you have no need of a template. Only if you have steps that are shared by various implementations of the algorithm do you need to work with a template.
Template method
defines the steps to execute an algorithm and it can provide default
implementation that might be common for all or some of the subclasses.
The template method pattern is used to define the basic steps of an algorithm and allow the implementation of the individual steps to be changed. This is similar to the strategy design pattern. The key difference is the ability to vary parts of the algorithm rather than replacing the algorithm in its entirety.
The overall structure of the basic algorithm is defined in an abstract base class. This class may include some real functionality but often just defines the order in which the overridable steps will be executed.
The implementations for the steps are defined in subclasses. This use of inheritance promotes loose coupling, as the calling function need not know which algorithm is to be executed. Correct use of the pattern also reduces duplication of code.
Example 1 : Creating robots by template
If you had a template method to base robots on, you could make use of it in an inheriting class as illustrated
If you had a template method to base robots on, you could make use of it in an inheriting class as illustrated
dddddd
Lets talk about Cookie class
1: public abstract class RobotTemplate {
2: public final void go() {
3: start();
4: getParts();
5: assemble();
6: test();
7: stop();
8: }
9: public void start() {
10: System.out.println("Starting....");
11: }
12: public void getParts() {
13: System.out.println("Getting parts....");
14: }
15: public void assemble() {
16: System.out.println("Assembling....");
17: }
18: public void test() {
19: System.out.println("Testing....");
20: }
21: public void stop() {
22: System.out.println("Stopping....");
23: }
24: }
1: public abstract class RobotTemplate {
2: public final void go() {
3: start();
4: getParts();
5: assemble();
6: test();
7: stop();
8: }
9: public void start() {
10: System.out.println("Starting....");
11: }
12: public void getParts() {
13: System.out.println("Getting parts....");
14: }
15: public void assemble() {
16: System.out.println("Assembling....");
17: }
18: public void test() {
19: System.out.println("Testing....");
20: }
21: public void stop() {
22: System.out.println("Stopping....");
23: }
24: }
1: public class AutomotiveRobot extends RobotTemplate {
2: private String name;
3: public AutomotiveRobot(String n) {
4: name = n;
5: }
6: public void getParts()
7: {
8: System.out.println("Getting a carburetor....");
9: }
10: public void assemble()
11: {
12: System.out.println("Installing the carburetor....");
13: }
14: public void test()
15: {
16: System.out.println("Revving the engine....");
17: }
18: //NEW method added
19: public String getName() {
20: return name;
21: }
22: }
Now Let's Test this class
1: public class TestTemplate {
2: public static void main(String[] args) {
3: AutomotiveRobot automotiveRobot = new AutomotiveRobot(
4: "Automotive Robot");
5: CookieRobot cookieRobot = new CookieRobot("Cookie Robot");
6: System.out.println(automotiveRobot.getName() + ":");
7: automotiveRobot.go();
8: System.out.println();
9: System.out.println(cookieRobot.getName() + ":");
10: cookieRobot.go();
11: }
12: }
Output of the program
Automotive Robot:
Starting....
Getting a carburetor....
Installing the carburetor....
Revving the engine....
Stopping....
Cookie Robot:
Starting....
Getting flour and sugar....
Baking a cookie....
Crunching a cookie....
Stopping....
Adding
a hook
You can also
provide hooks into your algorithm. A hook is a method that controls
some aspect of that
algorithm.
For
example,
if you wanted to make the testing part of the Robot algorithm optional, you
could surround that part with a conditional whose condition is set by a hook
method named testOK.
You use the
Template Method design pattern when you’ve got an algorithm of several steps
and you want to allow customization by subclasses. It’s that easy. Implement
the steps in that algorithm as an overridable method calls in an abstract
class, and let the subclasses override those steps as required. The Template
Method pattern is great when you have a multi-step algorithm to implement that
you also want to customize
Example 2 :
We're going to create a 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 extend Game and override its methods.
1: public abstract class Game {
2: void toss (){
3: System.out.println("Check which team win the toss");
4: }
5: abstract void initialize();
6: abstract void startPlay();
7: abstract void endPlay();
8: //template method
9: public final void play(){
10: //initialize the game
11: initialize();
12: //default implemented method
13: toss();
14: //start game
15: startPlay();
16: //end game
17: endPlay();
18: }
19: }
1: public class Football extends Game {
2: @Override
3: void endPlay() {
4: System.out.println("Football Game Finished!");
5: }
6: @Override
7: void initialize() {
8: System.out.println("Football Game Initialized! Start playing.");
9: }
10: @Override
11: void startPlay() {
12: System.out.println("Football Game Started. Enjoy the game!");
13: }
14: }
1: public class Cricket extends Game {
2: @Override
3: void endPlay() {
4: System.out.println("Cricket Game Finished!");
5: }
6: @Override
7: void initialize() {
8: System.out.println("Cricket Game Initialized! Start playing.");
9: }
10: @Override
11: void startPlay() {
12: System.out.println("Cricket Game Started. Enjoy the game!");
13: }
14: }
1: public class TemplatePatternDemo {
2: public static void main(String[] args) {
3: Game game = new Cricket();
4: game.play();
5: System.out.println();
6: game = new Football();
7: game.play();
8: }
9: }
Output of program
Cricket Game
Initialized! Start playing.
Check which team
win the toss
Cricket Game
Started. Enjoy the game!
Cricket Game
Finished!
Football Game
Initialized! Start playing.
Check which team
win the toss
Football Game
Started. Enjoy the game!
Football Game
Finished!
Notes :
To make sure that subclasses don’t override the template method, we should make it final.
Usage
The template method is used in frameworks, where each implements the invariant parts of a domain's architecture, leaving "placeholders" for customization options. This is an example for inversion of control, also called the Hollywood principle
Check list
- Examine the algorithm, and decide which steps are standard and which steps are peculiar to each of the current classes.
- Define a new abstract base class to host the "don't call us, we'll call you" framework.
- Move the shell of the algorithm (now called the "template method") and the definition of all standard steps to the new base class.
- Define a placeholder or "hook" method in the base class for each step that requires many different implementations. This method can host a default implementation – or – it can be defined as abstract (Java) or pure virtual (C++).
- Invoke the hook method(s) from the template method.
- Each of the existing classes declares an "is-a" relationship to the new abstract base class.
- Remove from the existing classes all the implementation details that have been moved to the base class.
- The only details that will remain in the existing classes will be the implementation details peculiar to each derived class.
Template Method Pattern in JDK
- All non-abstract methods of java.io.InputStream, java.io.OutputStream, java.io.Reader and java.io.Writer.
- All non-abstract methods of java.util.AbstractList, java.util.AbstractSet and java.util.AbstractMap.
Rules of thumb
- Strategy is like Template Method except in its granularity.
- Template Method uses inheritance to vary part of an algorithm. Strategy uses delegation to vary the entire algorithm.
- Strategy modifies the logic of individual objects. Template Method modifies the logic of an entire class.
- Factory Method is a specialization of Template Method.
- The strategy pattern is with Template Method pattern. The difference consists in the fact that Strategy uses delegation while the Template Methods uses the inheritance.
Second
No comments:
Post a Comment