intermediateTemplate Method Pattern

Most behavioral patterns favor composition over inheritance. Why does Template Method deliberately do the opposite?

Composition is usually preferred because it keeps classes loosely coupled and lets behavior be swapped at runtime, but Template Method's entire goal is the opposite of swappable — it needs to guarantee that a fixed sequence of steps can never be rearranged by anything using it, while still allowing exactly one specific step to vary. Inheritance, paired with a final orchestrating method and a protected abstract or hook method for the varying step, directly enforces that constraint at compile time: a subclass literally cannot override the sequencing method, and it must (for abstract steps) or may (for hooks) supply its own version of the customizable step. Composition could not enforce that same guarantee nearly as directly, since a composed strategy object could always be called in the wrong order by whatever holds it. This is a case where inheritance's tighter coupling is genuinely the right tool for the job rather than a design smell.

Ready to master this question?

Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.

Sign in to generate a response

Next Step

Continue to What is the core criticism of the Singleton pattern, and what would a better alternative look like in a Spring application?← Back to all Low-Level Design & Design Patterns questions