What is strategy pattern ?
Strategy is a behavioral design pattern that lets you define a family of algorithms, put each of them into a separate class, and make their objects interchangeable.
How it works
Strategy Interface: A common interface or abstract class is defined to represent the algorithm's behavior.
Concrete Strategies: Concrete classes implement the strategy interface, providing a specific algorithm or behavior. Each concrete strategy encapsulates a particular way to perform a task.
Context: The context is the class that uses a strategy. It holds a reference to a strategy object and delegates the task to it instead of executing the logic itself. The context can be configured with a different strategy object at runtime.
Client: The client code is responsible for creating the context and choosing which concrete strategy to pass to it.
Why Use Strategy Pattern?
It helps you:
✔ Remove long if/else or switch blocks
✔ Isolate different behaviors into separate classes
✔ Add new behaviors without modifying existing code (Open/Closed Principle)
✔ Make your application cleaner, modular, testable, and extendable
Real-Life Example
Think of a payment service:
Pay with PayPal
Pay with Credit Card
Pay with Google Pay
Without Strategy Pattern → you'd write big conditional logic.
With Strategy Pattern → you create a separate “strategy” class for each payment type.
Top comments (0)