What is the Strategy pattern, and how does it differ from the State pattern?
MediumConceptDesign Patterns
Answer
The Strategy pattern defines a family of interchangeable algorithms behind a common interface and lets the client choose one at run time, replacing long conditional chains.
interface PricingStrategy { double price(Ride ride); }
class SurgePricing implements PricingStrategy { ... }
rideService.setPricing(new SurgePricing());
- Uses: payment methods, ranking rules, discount calculation and spot allocation in a parking lot.
- Benefit: new algorithms are added as new classes without changing existing code, following the Open/Closed Principle.
- State vs Strategy: both delegate to an interchangeable object, but a State object represents the context's current state and transitions happen internally (a vending machine moving from
IdletoHasMoney), whereas a Strategy is usually chosen by the client and does not replace itself.
More in Design Patterns
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | What is the Singleton pattern, and what are its drawbacks? | Concept | Easy | Read the answer to What is the Singleton pattern, and what are its drawbacks? | |||
| 2 | What is the Factory pattern, and when would you use it? | Concept | Medium | Read the answer to What is the Factory pattern, and when would you use it? | |||
| 3 | How does the Observer pattern work, and where is it used? | Concept | Medium | Read the answer to How does the Observer pattern work, and where is it used? | |||
| 4 | What is the Strategy pattern, and how does it differ from the State pattern? | Concept | Medium | Read the answer to What is the Strategy pattern, and how does it differ from the State pattern? |