Study of GoF's Design Patterns (1994)
Define a family of algorithms, encapsulate each one, make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
Policy
Don't hardwire algorithms to classes that require them. What happens if algorithm changes? What if many classes commonly use this algorithm? What if bug is found, and it needs to be changed? Avoid duplicate code and support different algorithms using the same interface.
diagram from book
In this case, Composition
class uses Compositor
class to call Compose()
, which manipulates Composition
's members. But which compositor it uses can vary, even at runtime.
Strategy
(Compositor)ConcreteStrategy
Context
(Composition)ConcreteStrategy
objectStrategy
ObjectStrategy
and Context
. Relevant info, or Context
itself is passed. But some algorithms may not use all info, while some use all. If this is an issue, neee tighter coupling between Strategy
and Context
.Strategy
and Context
interfaces. Passing the Context
itself couples it, but allows explicit request to Context
from Strategy
. Or you can pass data as parameters to decouple it, but then might pass data that some algorithms don't need. Choose wisely.Strategy
objects optional. Check Context
checks if Strategy
objects exist. If not, carry out default behavior. if yes, use Strategy
. Benefit is clients don't have to deal with Strategy
objects at all, unless they don't like the default behavior.in book, C++.
Many known uses, but I know not one of these. Refer to book if needed
Flyweight Pattern