HuntExams Academy logo
JavaAdvanced#design-patterns

What is the Template Method pattern?

Answer

A behavioral pattern where an abstract class defines the skeleton of an algorithm in a method, deferring some steps to subclasses via abstract or overridable methods, ensuring the overall structure stays fixed.

Example

abstract class DataProcessor {
  final void process() { readData(); transformData(); saveData(); }
  abstract void transformData();
  void readData() { System.out.println("reading"); }
  void saveData() { System.out.println("saving"); }
}

Detailed explanation

The Template Method pattern is a behavioural design pattern in which a superclass defines an algorithm’s overall sequence while allowing subclasses to customise selected steps. The method containing this sequence is called the template method. It captures what must remain consistent, such as reading, transforming, and saving data, while delegating variable behaviour to abstract or overridable methods. This matters when several implementations share a workflow but differ in particular operations: common orchestration stays in one place instead of being duplicated across subclasses.

In the given Java example, process() is the template method because it calls readData(), transformData(), and saveData() in a fixed order. Declaring process() final prevents subclasses from overriding that orchestration. DataProcessor is abstract, and transformData() is abstract, so every concrete subclass must provide a transformation implementation, directly or through inheritance. The readData() and saveData() methods provide defaults that subclasses can override where Java’s access rules permit. Calling process() on a concrete processor executes the superclass workflow, but Java’s dynamic method dispatch selects the appropriate overridden implementation for each step.

Template methods commonly distinguish required operations, default operations, and hooks. Required operations are abstract methods; default operations have reusable implementations; hooks are optional extension points, often with empty bodies, such as afterSave(). Although final is not mandatory for recognising the pattern, it is useful when the workflow must not be overridden. In production code, process() might be public and extension points protected. The example uses package-private access, which limits direct subclass implementation outside its package. Also, final preserves the orchestration code, not every execution outcome: an overridden step can throw an exception, preventing later steps from running unless the template handles it.

Interviewers usually look for the distinction between fixed sequencing and variable steps, plus an understanding of inheritance-based reuse. Template Method follows inversion of control: the superclass calls subclass behaviour rather than the subclass controlling the entire workflow. Its trade-off is tighter coupling to the superclass contract, so changes to step ordering or assumptions can affect subclasses. If behaviour needs to be replaced independently at runtime, Strategy, which delegates to composed objects, is often a better fit.

Key points to remember

  • A superclass defines the algorithm’s skeleton; subclasses customise designated steps.
  • The template method controls sequencing and can be final to prevent overriding.
  • Abstract methods require implementations; default methods and hooks allow optional customisation.
  • Java’s dynamic dispatch invokes overridden steps within the inherited workflow.
  • Template Method uses inheritance, whereas Strategy uses composition and delegation.

Common mistakes candidates make

  • Claiming final is required by the pattern rather than a Java mechanism for enforcing fixed orchestration.
  • Assuming every step must be abstract, overlooking reusable defaults and optional hooks.
  • Saying final guarantees every step completes, ignoring exceptions and subclass behaviour.

Likely follow-up questions

How is Template Method different from Strategy?

Template Method customises selected steps through subclass overrides while keeping orchestration in a superclass. Strategy delegates behaviour to a separate object, making it easier to replace that behaviour at runtime when the design allows it.

What is a hook method?

A hook is an optional extension point called by the template method, usually with an empty or default implementation. Subclasses override it only when they need additional behaviour, unlike an abstract method that requires an implementation.

Can a subclass in another package implement the given DataProcessor example?

Not directly as written: DataProcessor and its methods have package-private access. For cross-package extension, make the class public, expose process() as appropriate, and declare extension points such as transformData() protected.

Interview tip: Walk through process() in order, identify transformData() as the required variation point, and briefly contrast inheritance-based customisation with Strategy.

Related Interview Questions

1
JavaBeginner#jdbc

What is JDBC and what are its main components?

Open
2
JavaBeginner#jdbc

What is the difference between Statement and PreparedStatement?

Open
3
JavaIntermediate#jdbc

What is a CallableStatement used for?

Open