Strategy

Puts a family of interchangeable algorithms behind one interface, so you can choose one at runtime.

Why it matters

When an algorithm can vary (pricing, sorting, routing), putting every variant in one method with if/else makes it long, hard to test and risky to extend.

The idea

Instead of an if/elif on pricing type inside checkout, each pricing rule is its own class (or function) with the same method. Checkout holds one strategy and can swap it.

Choosing a route in a maps app: fastest, shortest or avoiding tolls. Same journey, different strategy.

The maps app chooses for you when you tap a button. In code, something still has to decide which strategy to use, often a factory or configuration.

How it works

  1. Define the interface: price(distance_km).
  2. Write one class per algorithm: NormalPricing, SurgePricing, NightPricing.
  3. The context (Ride) holds one strategy object and calls it.
  4. Choose the strategy at runtime: from configuration, a factory, or the time of day.

Example

Payment fees, sorting, compression formats, and ride pricing (normal or surge).

Key points

Common mistakes

Not true: Every algorithm deserves its own strategy class, even when there will only ever be one.
In fact: With one fixed algorithm there is nothing to swap, so the pattern only adds classes. Use Strategy when several algorithms are interchangeable.

In the interview

Strategy puts each interchangeable algorithm, like normal or surge pricing, behind one interface, so the class using it can switch algorithms at runtime, and new ones are added without editing it.

Part of Unit 6: Design patterns in the free System Design course.