What is the Template Method pattern and when would you use it?

The Template Method pattern defines the skeleton of an algorithm in a base class method, deferring specific steps to subclasses. It's used whenever you have a process that must always follow the same overall sequence but needs different behavior for particular steps.

Key Points: • The base class controls the overall order of operations; subclasses only fill in the variable steps. • It promotes code reuse, since the shared steps live in one place instead of being duplicated across subclasses. • It's a good fit for workflows, algorithms, and report or document generation pipelines with a fixed shape. • It relies on inheritance, so it's less flexible at runtime than composition-based alternatives like Strategy. • Hook methods let subclasses optionally customize behavior without being forced to override every step.

Example: A test framework's runTest() method might always call setUp(), runTestCase(), and tearDown() in that order, letting each test class override only runTestCase().

Interview Tip: A concise interview answer is:

"Template Method fixes the shape of an algorithm in a base class and lets subclasses fill in specific steps, so I'd use it for processes like report generation or data import pipelines that always follow the same sequence but need different behavior at particular points. It's great for code reuse since the shared steps live in exactly one place."