Design Patterns interview question · Most asked

Explain the Strategy pattern with an example.

Summary

Strategy puts interchangeable algorithms behind one interface; a context holds one strategy and delegates to it, so the algorithm can be chosen at runtime without if/else. Shipping cost rules (standard, express, pickup) are a typical example.

Longer Answer

Each strategy is testable alone, and new ones are added without editing the context (Open/Closed). Selection usually happens once, through configuration or a lookup table. In Python, TypeScript, modern Java and PHP a strategy is often just a function or lambda; comparators passed to sort functions are strategies.

Code Example

STRATEGIES = {  # strategies as plain functions in a lookup table
    "standard": lambda subtotal: 0 if subtotal >= 5000 else 499,
    "express": lambda subtotal: 1299,
    "pickup": lambda subtotal: 0,
}


def total(subtotal, method):
    return subtotal + STRATEGIES[method](subtotal)


for method in ["standard", "express", "pickup"]:
    print(method, total(4200, method))

Key Points

  • Interchangeable algorithms behind one interface.
  • Context delegates; no if/else.
  • Often just a function.
  • Pick via lookup table or configuration.

Deep dive: Design Patterns, Explained Simply: Strategy

Explanation

What interviewers look for

A realistic example, the Open/Closed benefit, and recognising functions as strategies.

Follow-up questions

  • How is Strategy different from State?
  • How do you avoid an if/else just to pick the strategy?

More most-asked Design Patterns questions

← All Design Patterns questions