A Behavioural Design Pattern, similar to Template Method Pattern, except that it uses composition instead of inheritance to achieve it’s purpose. Objects created from this pattern can also switch strategies in runtime. In most cases, it’s better, as it reduces duplicate code (with the drawback of creating more classes).
Usecase
- When you have multiple ways to do something. I.e. you have multiple algorithms that all achieve the same purpose, but in different ways.
- When an object has multiple behaviours that all have some common traits and might need to change the behaviour in runtime.
Properties
- Context/Object: Our main class that will implement various strategies and can switch between them. It needs to store a reference to (aggregate) a strategy. For added functionality, it should have a public setter to change this reference at runtime.
- Strategy Interface: An interface which defines what each strategy’s goal is. While every strategy is different, they all need to share a common end goal.
- Concrete Strategy: A specific strategy, which Inheritance from the strategy interface.
Context doesn't switch strategies
In spite of the terribly chosen name, the Context class doesn’t change strategies based on context. It allows the client to do so, so the client code needs to implement switching, and needs to be aware of all the different strategies.
UML Class
classDiagram
class Context {
Strategy strategy
+setStrategy(Strategy newStrategy)
+runStrategy()
}
class Strategy {
+run()
}
class StrategyA
class StrategyB
<<interface>> Strategy
Strategy <|-- StrategyA
Strategy <|-- StrategyB
Context --o Strategy
Pros vs Cons
Pros
- Composition over inheritance. Allows multiple composed behaviours to be easily added, instead of chained, complicated inheritance trees.
- Easily switch strategy at runtime, allow flexibility.
- Open-Closed Principle: You can introduce new strategies without having to change the context.
Cons
- Creates a lot more classes, one for each strategy.
- Client needs to be aware of all strategy to make an informed choice of switching.
Example
- Different types of sorting algorithms can be employed based on the number of items that need to be solved.