Card 09/ 09
Recap: Strategy Pattern
The caller picks the algorithm, the context runs it, and in Python it is often a function.
Strategy replaces a conditional that chooses an algorithm with an object, or a function, that the caller hands in.
- Intent. Define a family of algorithms, encapsulate each one, and make them interchangeable.
- Participants. The strategy interface, one concrete strategy per algorithm, the context that holds one, and the client that chooses it.
- The choice. It is made by the caller and can be changed at any time; the context never branches on it.
- In the wild. Java's
Comparatorpassed toList.sort, and the function passed askeyto Python'ssorted. - In Python. A one-method strategy is a function; use a class for a second method or named configuration.
- The trap. A context that checks which strategy it holds; move that behaviour into the strategy.
- When not. Two fixed options, algorithms that need different inputs, or a choice that follows the object's own state.
← → move through sections and cards