Skip to content
We areTOP 1%

What is the Strategy pattern, and how does it differ from the State pattern?

MediumConceptDesign Patterns
Track your progress
First attempt
Re-solve after a few days
Final pass before interviews

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 Idle to HasMoney), whereas a Strategy is usually chosen by the client and does not replace itself.

More in Design Patterns

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account