loading...

Design Pattern: The Template Method Pattern

danlee0528 profile image Daniel Lee ・1 min read

The Template Method Pattern defines the skeleton of an algorithm in method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm structure

Diagram Example

  • Cricket and Football are concrete classes that implement abstract operations which are called when the template method needs them. i.e) initialize() method

Code Example

  • We abstract methods when your subclass MUST provide an implementation of the method or step in the algorithm
  • "Final" keyword prevents subclasses from changing the algorithm in the template method
abstract class AbstractClass{
    final void templateMethod(){
        primitiveOperation1();
        primitiveOperation2();
        concreteOperation();
        hook(); 
    }

    abstract void primitiveOperation1();
    abstract void primitiveOperation2();
    final void concreteOperation(){
        // implementation here
    }   
    void hook(){
        // implementation here
    }

}

Discussion

pic
Editor guide