Strategy

Beginner · 15 min read · Low-Level Design, Behavioral Patterns

Interchangeable algorithms behind one interface.

The idea in plain words

There are several ways to do the same job. Put each way in its own class behind one shared interface, and choose which one to use at runtime. The code that needs the job done only knows the interface.

The problem

A parking lot computes fees. Initially: hourly. Then: flat rate for events, weekend rates, EV discounts, monthly passes.

The solution

Adding a "festival surge" rule is a new class; ExitGate never changes.

Choosing the strategy

Something has to pick the strategy — keep that decision in one place:

Lambdas: the lightweight strategy

In Java 8+, any functional interface is a strategy slot. Comparator is the most familiar strategy in the JDK:

Where you've seen it

Strategy in LLD case studies

Pros and cons

Comparisons

Interview questions

  • How does Strategy help with the Open/Closed Principle?
  • Who should decide which strategy to use?
  • When would you use a lambda instead of a strategy class?

Further reading

Key takeaways

  • Strategy puts interchangeable algorithms behind one interface; the context delegates.
  • It replaces conditionals with polymorphism and keeps each algorithm testable in isolation.
  • Keep strategy selection in one place (client, configuration or a selector).
  • It is the most common pattern in machine-coding problems.

Previous: Flyweight · Next: Observer