DEV Community

eidher
eidher

Posted on • Updated on

Template Method Pattern

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.

Alt Text

Participants

  • AbstractClass: defines abstract primitive operations that concrete subclasses define to implement steps of an algorithm. Implements a template method defining the skeleton of an algorithm. The template method calls primitive operations as well as operations defined in AbstractClass or those of other objects.
  • ConcreteClass: implements the primitive operations ot carry out subclass-specific steps of the algorithm

Code

public class Main {

    public static void main(String[] args) {
        AbstractClass aA = new ConcreteClassA();
        aA.templateMethod();
        AbstractClass aB = new ConcreteClassB();
        aB.templateMethod();
    }
}

public abstract class AbstractClass {

    public abstract void primitiveOperation1();

    public abstract void primitiveOperation2();

    public void templateMethod() {
        primitiveOperation1();
        primitiveOperation2();
    }
}

public class ConcreteClassA extends AbstractClass {

    @Override
    public void primitiveOperation1() {
        System.out.println("ConcreteClassA.primitiveOperation1()");
    }

    @Override
    public void primitiveOperation2() {
        System.out.println("ConcreteClassA.primitiveOperation2()");
    }
}

public class ConcreteClassB extends AbstractClass {

    @Override
    public void primitiveOperation1() {
        System.out.println("ConcreteClassB.primitiveOperation1()");
    }

    @Override
    public void primitiveOperation2() {
        System.out.println("ConcreteClassB.primitiveOperation2()");
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

ConcreteClassA.primitiveOperation1()
ConcreteClassA.primitiveOperation2()
ConcreteClassB.primitiveOperation1()
ConcreteClassB.primitiveOperation2()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)