This design defines a set of algorithms, encapsulates each one, and makes them interchangeable. It enables a client to select an algorithm from a family of algorithms at runtime and provides a simple interface to access it.
Examples of Strategy Patterns
Examples of strategy patterns include:
Discount Strategy
Payment Strategy
Strategy Pattern with UML diagram
The classes, interfaces, & objects in the above UML class diagram are defined as follows:
Context: This is a class with a property that stores the reference to a Strategy object. This property will be set at runtime based on the necessary algorithm.
Strategy: This interface allows the Context object to call the algorithm provided by a ConcreteStrategy.
ConcreteStrategyA/B: These classes implement the Strategy interface.
When Should the Strategy Design Pattern Be Used?
The Strategy design pattern is applicable in the following scenarios:
There are several strategies for a given problem, and the selection criteria for each strategy are established at runtime.
Many related classes just differ in their behavior.
The strategies rely on data to which the client has no access.
Advantages of the Strategy Design Pattern
Flexibility: The ability to flexibly change the behavior of an object.
Loose Coupling: The strategy classes are independent of one other and the context class, allowing for loose coupling.
Reuse: Strategies can be applied in a variety of settings.
Isolation: Each approach may be implemented and maintained independently of the others.
Open/Closed Principle: New strategies can be implemented without altering the context.