Skip to content
LLD Learn/Behavioral Patterns
Browsing as a guest. Sign in to save your progress and earn XP as you complete chapters.

Strategy

3 min read

You'll learn to

  • -Explain Strategy as "the way of doing it is an object you hand in", with a maps-app picture
  • -Run a pricing example where the rule changes without touching the order class
  • -Tell Strategy from State by asking who chooses the behavior

Open a maps app and you can pick a route type: fastest, shortest, or avoid tolls. The destination is the same and the app is the same. Only the way of working out the route changes, and you choose it. That is Strategy: define a family of interchangeable ways of doing one job, put each behind the same interface, and let the caller hand in the one it wants.

It is arguably the most commonly applied pattern in LLD interviews, because "this behavior needs to vary" is one of the most common shapes a requirement takes. Pricing rules, payment methods, sorting orders and fare calculations are all strategies.

The Canonical Shape

The demo prices one order under three rules. The Order class holds a pricing strategy and asks it for the total. It never checks which rule it was given.

Press Run: one Order class, three prices for the same 100.00 item

This Is How Open/Closed Actually Gets Satisfied

Recall the growing if/elif chain from the Open/Closed chapter. Strategy is the concrete mechanism that removes it. Order never branches on the pricing type. Adding a Black Friday rule means writing one new class, with no change to Order and no risk to the existing rules.

Strategy vs. State

Strategy and State look nearly identical in code, because both hold an object behind an interface and hand work to it. The difference is who decides. With Strategy, the caller explicitly chooses the behavior: a checkout picks the holiday pricing because it is holiday season. With State (a later chapter), the object switches its own behavior as it moves through its life, and the caller never picks directly. A music player that behaves differently when playing than when paused is State.

A fast test: if the design says "the caller passes in which behavior to use", it is Strategy. If the object decides to switch behavior because of its own events, look at State.

Interview Signal is part of Pro

See a real weak answer next to a real strong one for this exact topic.

Quiz is part of Pro

Test what you just read with a short quiz, and bank the XP.

Discussion0

Join the Discussion

Sign in to leave comments, reply to others, or like insights.

Sign In to ScaleDojo

No comments yet. Be the first to start the thread!