What is Template Method pattern? Explain with example.

What is Template Method pattern? Explain with example.

Ninja Asked on 18th September 2018 in Design Pattern.
Add Comment
1 Answer(s)
Best answer

Template Method pattern is a behavioral pattern which is used to manage algorithms. Template Method pattern is used when two or more implementations of a similar algorithm exist. As per GoF, intent of Template Method pattern is “Defines the skeleton of an algorithm in a method, deferring some steps to subclasses”.

In Template Method pattern, an abstract clasas exposes defined way(s)/template(s) to execute its methods. Its subclasses can override the method implementations as per need basis but the invocation is to be in the same way as defined by the abstract super class.

Let us understand this with an example: In this example, Parser is the abstract super class that defines the algorithm which is implemented by the subclasses XMLParser and JSONParser.

public abstract class Parser {// Template Method – final so that subclasses don’t override

public final void parse() {

readData();

processData();

displayOutput();

}

public abstract void readData();

public void processData() {

// Process data from the parser….

System.out.println(“Processing data….”);

}

public abstract void displayOutput();

}

public class XMLParser extends Parser{@Override

public void readData() {

System.out.println(“Reading data from XML file….”);

}

@Override

public void displayOutput() {

System.out.println(“Displays output from parsed XML file….”);

}

}

 

public class JSONParser extends Parser {@Override

public void readData() {

System.out.println(“Reading JSON objects….”);

}

@Override

public void displayOutput() {

System.out.println(“Displays output from JSON objects….”);

}

}

 

public class TestTemplate {

public static void main(String[] args) {

Parser parser = new XMLParser();

parser.parse();

parser = new JSONParser();

parser.parse();

}

}

Output:

Reading data from XML file….

Processing data….

Displays output from parsed XML file….

Reading JSON objects….

Processing data….

Displays output from JSON objects….

Interesting point to note in template method pattern is that superclass template method calls methods from subclasses.

Ninja Answered on 18th September 2018.
Add Comment