Understanding the Problem: Building Different Types of Houses
When building any house—whether a Glass House or a Wooden House—the sequence of construction remains identical:
Build the foundation
Build the pillars
Build the walls
Build the windows
While the overall sequence never changes, the materials used in each step vary. For a wooden house, you use wood coatings and wooden walls. For a glass house, you use glass coatings and glass panels.
The Template Method Solution
Instead of rewriting the construction sequence in every subclass, we define the entire workflow once inside an abstract class called HouseTemplate:
Template Method (buildHouse()): Declared as final so subclasses cannot alter the sequence of construction.
Abstract Primitive Methods:buildFoundation(), buildPillars(), buildWalls(), and buildWindows() are left abstract for subclasses to provide specific material logic.
Java Code Implementation
Here is how the template pattern structure is set up in Java:
// Abstract Template Class
public abstract class HouseTemplate {
// Template method defining the construction sequence
public final void buildHouse() {
buildFoundation();
buildPillars();
buildWalls();
buildWindows();
System.out.println("House is built successfully!\n");
}
public abstract void buildFoundation();
public abstract void buildPillars();
public abstract void buildWalls();
public abstract void buildWindows();
}
Concrete classes such as WoodenHouse and GlassHouse extend HouseTemplate and supply custom logic for building with wood or glass. The client class HousingClient simply calls buildHouse(), keeping client code simple, decoupled, and clean.
No comments:
Post a Comment