The Strategy Design Pattern is a behavioral design pattern that defines a family of algorithms, encapsulates each one, and makes them interchangeable. This allows the algorithm to vary independently from the clients that use it.
Intent
- Enable a client to select an algorithm or behavior at runtime.
- Promote the Open/Closed Principle: New algorithms can be added without modifying existing code.
Key Components
- Strategy Interface: Common interface for all supported algorithms.
- Concrete Strategies: Implementations of the strategy interface, representing different algorithms or behaviors.
- Context: Maintains a reference to a strategy object and delegates the behavior to the current strategy.
When to Use
- When multiple algorithms can be applied to solve a problem, and the decision of which algorithm to use is determined at runtime.
- To eliminate conditional statements (
if-else
orswitch
) for selecting behaviors. - When you want to make algorithms easily interchangeable and independent of the client.