SOLID & Design Patterns Interview Question #60

What is the difference between Strategy and Template Method?

Advanced Patterns, CQRS & Domain-Driven Design Fundamentals Mid-Level Intermediate

Quick Interview Answer

Strategy uses composition: an object delegates a variable algorithm to another object implementing a common abstraction. Template Method uses inheritance: a base class defines the algorithm structure and subclasses override selected steps.

Detailed Explanation

Strategy uses composition: an object delegates a variable algorithm to another object implementing a common abstraction. Template Method uses inheritance: a base class defines the algorithm structure and subclasses override selected steps.

Strategy generally provides greater runtime flexibility and avoids inheritance coupling. Template Method can be concise when the workflow is stable and subclass variation is natural.

Code Example

// Strategy
public class PricingService
{
    private readonly IPricingStrategy _strategy;
}

// Template Method
public abstract class Importer
{
    public void Run()
    {
        Read();
        Validate();
        Save();
    }

    protected abstract void Read();
    protected abstract void Validate();
    protected abstract void Save();
}