0% found this document useful (0 votes)
6 views5 pages

Understanding Template Method Pattern

The Template Method Design Pattern defines a fixed sequence of steps for executing an algorithm, allowing subclasses to provide specific implementations for certain steps while maintaining a common structure. An example is given with a house-building algorithm where methods for building walls and pillars can be overridden by subclasses like WoodenHouse and GlassHouse. The pattern emphasizes that the template method should be final to prevent overriding and that it often calls subclass methods, adhering to the Hollywood Principle.

Uploaded by

Suresh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views5 pages

Understanding Template Method Pattern

The Template Method Design Pattern defines a fixed sequence of steps for executing an algorithm, allowing subclasses to provide specific implementations for certain steps while maintaining a common structure. An example is given with a house-building algorithm where methods for building walls and pillars can be overridden by subclasses like WoodenHouse and GlassHouse. The pattern emphasizes that the template method should be final to prevent overriding and that it often calls subclass methods, adhering to the Hollywood Principle.

Uploaded by

Suresh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Template Method Design Pattern

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.
Let’s understand this pattern with an example, suppose we want to provide an
algorithm to build a house. The steps need to be performed to build a house
are – building foundation, building pillars, building walls and windows. The
important point is that the we can’t change the order of execution because we
can’t build windows before building the foundation. So in this case we can
create a template method that will use different methods to build the house.
Now building the foundation for a house is same for all type of houses,
whether its a wooden house or a glass house. So we can provide base
implementation for this, if subclasses want to override this method, they can
but mostly it’s common for all the types of houses.
To make sure that subclasses don’t override the template method, we should
make it final.

Template Method Abstract Class

Since we want some of the methods to be implemented by subclasses, we


have to make our base class as abstract class.
[Link]

package [Link];

public abstract class HouseTemplate {

//template method, final so subclasses can't override


public final void buildHouse(){
buildFoundation();
buildPillars();
buildWalls();
buildWindows();
[Link]("House is built.");
}
//default implementation
private void buildWindows() {
[Link]("Building Glass Windows");
}

//methods to be implemented by subclasses


public abstract void buildWalls();
public abstract void buildPillars();

private void buildFoundation() {


[Link]("Building foundation with
cement,iron rods and sand");
}
}
buildHouse()is the template method and defines the order of execution for
performing several steps.

Template Method Concrete Classes

We can have different type of houses, such as Wooden House and Glass
House.
[Link]

package [Link];

public class WoodenHouse extends HouseTemplate {

@Override
public void buildWalls() {
[Link]("Building Wooden Walls");
}

@Override
public void buildPillars() {
[Link]("Building Pillars with Wood
coating");
}

We could have overridden other methods also, but for simplicity I am not
doing that.
[Link]

package [Link];

public class GlassHouse extends HouseTemplate {

@Override
public void buildWalls() {
[Link]("Building Glass Walls");
}

@Override
public void buildPillars() {
[Link]("Building Pillars with glass
coating");
}

Template Method Design Pattern Client

Let’s test our template method pattern example with a test program.
[Link]

package [Link];

public class HousingClient {

public static void main(String[] args) {

HouseTemplate houseType = new WoodenHouse();

//using template method


[Link]();
[Link]("************");

houseType = new GlassHouse();

[Link]();
}

}
Notice that client is invoking the template method of base class and
depending of implementation of different steps, it’s using some of the methods
from base class and some of them from subclass.
Output of the above program is:

Building foundation with cement,iron rods and sand


Building Pillars with Wood coating
Building Wooden Walls
Building Glass Windows
House is built.
************
Building foundation with cement,iron rods and sand
Building Pillars with glass coating
Building Glass Walls
Building Glass Windows
House is built.

Template Method Class Diagram

Template Method Design Pattern in JDK

 All non-abstract methods of [Link], [Link],


[Link] and [Link].
 All non-abstract methods of [Link], [Link] and
[Link].
Template Method Design Pattern Important Points

1. Template method should consists of certain steps whose order is fixed and for
some of the methods, implementation differs from base class to subclass.
Template method should be final.
2. Most of the times, subclasses calls methods from super class but in template
pattern, superclass template method calls methods from subclasses, this is
known as Hollywood Principle – “don’t call us, we’ll call you.”.
3. Methods in base class with default implementation are referred as Hooks and
they are intended to be overridden by subclasses, if you want some of the
methods to be not overridden, you can make them final, for example in our
case we can make buildFoundation() method final because if we don’t want
subclasses to override it.

Thats all for template method design pattern in java, I hope you liked it.

Common questions

Powered by AI

The Hollywood Principle, "don’t call us, we’ll call you,” is utilized in the Template Method pattern by allowing the abstract superclass to dictate the algorithm's structure and call subclass implementations of certain methods. For instance, in the HouseTemplate class, the template method buildHouse() controls the order and calls the subclass methods like buildWalls() and buildPillars() as needed. This inversion of control ensures that subclasses only provide specific implementations when called by the superclass, adhering to the principle .

Hooks in the Template Method pattern are methods in the base class with default implementations that subclasses can override to change or extend certain behaviors. They enable flexibility while keeping the structure of the algorithm fixed. For example, in HouseTemplate, the hook methods like buildWindows can be overridden by subclasses like WoodenHouse to provide specific implementations (e.g., wooden or glass windows). Hooks allow subclasses to customize certain steps without altering the overall algorithm sequence.

The Template Method design pattern supports the Open/Closed Principle by allowing classes to be open for extension but closed for modification. The algorithm's structure is fixed in a final method of the superclass, which prevents modification. However, it allows subclasses to provide specific implementations for certain steps of the algorithm, thereby extending the default behavior without altering the superclass's code. This way, new functionalities can be added through subclassing, reflecting the principle .

It is important for the template method to be final to prevent subclasses from modifying the order of operations within the algorithm defined by the template method. This ensures consistency and correctness in execution, especially when order dependency is crucial, such as building a foundation before walls. If the template method were not final, subclasses could alter the execution order, potentially leading to invalid or inconsistent results, such as trying to build walls without a foundation .

The Template Method design pattern uses a final template method to define the fixed order of steps required to execute an algorithm, such as building a house. This method is marked as final to prevent subclasses from altering the sequence. The fixed order is crucial because certain steps depend on the completion of previous ones, such as building windows, which cannot start before the foundation is complete .

The java.util.AbstractList class in the JDK uses the Template Method pattern to define general algorithms for list operations with some method skeletons and default behaviors. For instance, the add() method relies on the abstract add(int index, E element) method, which needs implementation in a concrete subclass. This pattern ensures that all subclasses of AbstractList follow a specific protocol when adding elements while allowing customization of the underlying implementation behavior .

A subclass might choose not to override certain methods if the default implementation provided by the superclass meets its requirements. This decision is reflected in the pattern's implementation, as these methods remain unchanged in the subclass. For instance, in the GlassHouse subclass, the default buildFoundation() method of HouseTemplate is not overridden because the foundation is common across house types, thus simplifying the subclass's implementation .

The Template Method pattern facilitates code reuse by defining the common steps of an algorithm in a base class and allowing subclasses to provide specific implementations for some steps. In the house building scenario, the base class HouseTemplate provides reusable implementation for building a foundation which is common across different types of houses like WoodenHouse and GlassHouse. These subclasses reuse the foundation code and only need to implement specific methods for pillars and walls, reducing code duplication .

A client interacts with the Template Method pattern by invoking the template method of the base class through an instance of a subclass. For example, in HousingClient, the client creates an instance of WoodenHouse and calls buildHouse(), which is defined in the HouseTemplate. The template method then calls specific subclass implementations for building walls and pillars, while foundational steps are handled by default implementations in HouseTemplate .

In the Template Method pattern, abstract classes define the algorithm's structure and provide both final template methods and abstract methods that require subclass implementations. Concrete classes extend these abstractions to implement the specific behaviors required for certain algorithmic steps, maintaining the overall sequence dictated by the superclass. Abstract classes ensure the consistency of the algorithm flow, while concrete classes introduce variability where needed, such as different materials for walls and pillars in the WoodenHouse and GlassHouse classes .

You might also like