Strategy and Template Method both let you vary part of an algorithm, but they do it through different mechanisms: Strategy uses composition to swap an entire algorithm, while Template Method uses inheritance to customize individual steps of a fixed algorithm.
Key Points: • Strategy encapsulates a whole algorithm behind an interface and lets the client inject a different implementation at runtime. • Template Method defines the overall algorithm skeleton in a base class method and lets subclasses override specific steps. • Strategy favors composition ("has-a" relationship with the interface); Template Method favors inheritance ("is-a" relationship with the base class). • Strategy is more flexible since strategies can be swapped at runtime; Template Method's structure is fixed at compile time via subclassing. • Strategy fits interchangeable algorithms (e.g., sorting or payment methods); Template Method fits processes with a shared structure but different details (e.g., report generation steps).
Interview Tip: A concise interview answer is:
"Strategy swaps out an entire algorithm through composition — you inject a different implementation of the same interface. Template Method fixes the overall algorithm's structure in a base class and only lets subclasses override specific steps, so it relies on inheritance rather than composition and is less flexible at runtime."