We use analytics cookies.We use cookies to analyze site traffic and improve your experience.
Loading...
System Design Masterclass · Microservices Architecture
Free preview: the first 2 parts of this 7-part lesson.
Already bought the course? Sign in to read the whole lesson.
this lesson is part of
System Design Masterclass
Unlock this lesson and the 751 other paid lessons
$25 once, by PayPal
See the System Design courseread the rest of this lesson in
System Design Masterclass
Unlock this lesson and the 751 other paid lessons
$25 once, by PayPal
See the System Design coursein Microservices Architecture
This lesson is part of the full System Design Masterclass. Unlock it along with 769 other lessons for a one-time payment.
One-time payment by card or PayPal
Get Lifetime AccessOne-time payment: UPI, card or netbanking
Get Lifetime Access18 Foundation lessons are free, no payment needed. Try them now
It is easy and good
“It is really nice and good Please join the course”
Every developer has written this code at some point:
if (shippingMethod === "standard") {
cost = weight * 0.5;
} else if (shippingMethod === "express") {
cost = weight * 1.5 + 5.0;
} else if (shippingMethod === "overnight") {
cost = weight * 3.0 + 15.0;
} else if (shippingMethod === "drone") {
cost = weight * 5.0 + 25.0;
} else if (shippingMethod === "same-day") {
// ...
}
Every time the business adds a new shipping method, you open this file, add another else if, and hope you don't break the existing ones. This function violates the Open/Closed principle, it should be open for extension but closed for modification. Instead, it's a magnet for changes.
The Strategy pattern says: each shipping calculation is its own encapsulated algorithm. You pick which one to use at runtime. Adding a new shipping method means creating a new strategy class, you never touch the existing code.
The Strategy pattern lets you define a family of algorithms, encapsulate each one, and make them interchangeable. The code that uses the algorithm doesn't know or care which specific implementation it's running.
Think of it like a GPS navigation app. You tell it "get me to the airport." The app has multiple routing strategies, fastest route, shortest distance, avoid highways, avoid tolls. You pick one, and the app uses that strategy to compute directions. The navigation UI doesn't change. The map rendering doesn't change. Only the routing algorithm swaps.
| Component | Role | Example |
|---|---|---|
| Context | Uses a strategy, doesn't know which one | Navigation app, payment processor |
| Strategy interface | Defines what every algorithm must do | calculateRoute(), calculateCost() |
| Concrete strategies | Different implementations | FastestRoute, ShortestDistance, AvoidHighways |
The context holds a reference to a strategy interface. You can swap the concrete strategy at any time, at startup via config, at runtime via user choice, or dynamically based on conditions.