Behavioral PatternsTemplate Method PatternMedium⏱️ ~2 min

Template Method Structure: Components and Relationships

The Template Method Pattern consists of an abstract class that defines the algorithm structure and concrete subclasses that implement specific steps. Understanding the relationship between template methods and hook methods is crucial for proper implementation.

AbstractClass
+ templateMethod(): void
# primitiveOperation1(): void
# primitiveOperation2(): void
# hook(): void
ConcreteClassA
# primitiveOperation1(): void
# primitiveOperation2(): void
ConcreteClassB
# primitiveOperation1(): void
# primitiveOperation2(): void
# hook(): void

Key Components:

First, AbstractClass: Contains the templateMethod() that defines the algorithm skeleton. This method should be final to prevent modification. It calls primitive operations and hooks in a specific order.

Second, Primitive Operations: Abstract methods (primitiveOperation1(), primitiveOperation2()) that must be implemented by all subclasses. These represent the customizable steps of the algorithm.

Third, Hook Methods: Optional methods with default (often empty) implementations that subclasses can override if needed. Hooks provide extension points without forcing all subclasses to implement them.

Fourth, ConcreteClass: Implements the abstract primitive operations and optionally overrides hooks to customize behavior.

Template Method Pseudocode:
templateMethod():
  primitiveOperation1()
  primitiveOperation2()
  if hook() then
    // optional behavior
  end
  finalOperation()
Interview Tip: Distinguish between abstract primitive operations (must implement) and hooks (optional). Hooks enable the Open/Closed Principle by allowing extension without modification.

Method Visibility: Template methods are typically public (callable by clients), primitive operations are protected (only for subclass implementation), and hooks are protected with default implementations.

💡 Key Takeaways
AbstractClass defines templateMethod() with algorithm skeleton
Primitive operations are abstract methods requiring subclass implementation
Hook methods are optional with default implementations
Template method should be final/sealed to preserve structure
Protected visibility for primitive operations prevents external misuse
📌 Examples
1Abstract templateMethod() calls boilWater(), brew(), pourInCup(), addCondiments()
2Hook method customerWantsCondiments() provides optional customization point
← Back to Template Method Pattern Overview