Template Pattern

Category : Design Patterns | Sub Category : Behavioral Design Patterns | By Prasad Bonam Last updated: 2023-07-09 14:50:30 Viewed : 79

Template Pattern:

The Template Method pattern is a behavioral design pattern that defines the skeleton of an algorithm in a base class, allowing subclasses to provide specific implementations for certain steps of the algorithm. It promotes code reuse and provides a way to define the overall structure of an algorithm while allowing specific steps to be overridden by subclasses. Here is an example of implementing the Template Method pattern in Java:

// Abstract class defining the template method abstract class AbstractClass { public final void templateMethod() { // Perform common steps here // Call the abstract methods step1(); step2(); // Perform additional common steps here } protected abstract void step1(); protected abstract void step2(); } // Concrete subclass implementing the template methods class ConcreteClass extends AbstractClass { @Override protected void step1() { System.out.println("Step 1"); } @Override protected void step2() { System.out.println("Step 2"); } } // Client code public class Client { public static void main(String[] args) { AbstractClass abstractClass = new ConcreteClass(); abstractClass.templateMethod(); } }

In this example:

  • The AbstractClass defines the template method templateMethod(), which represents the overall algorithm. It consists of multiple steps, some of which are abstract methods that must be implemented by subclasses.
  • The ConcreteClass is a concrete subclass that extends the AbstractClass and provides specific implementations for the abstract methods step1() and step2().
  • The client code in the Client class demonstrates the usage of the template method pattern. It creates an instance of the ConcreteClass and calls the templateMethod(). The template method executes the algorithm defined in the abstract class, including the common steps and the specific steps implemented by the concrete subclass.

By using the Template Method pattern, you can define the overall structure of an algorithm in a base class while allowing specific steps to be implemented in subclasses. It promotes code reuse, reduces duplication, and enforces the defined structure of an algorithm. The template method provides a way to create frameworks or libraries that define the skeleton of an algorithm, allowing clients to customize certain steps as needed.

Related Articles

Leave a Comment: