Card 02/ 09

ConceptDifficulty: Intermediate1 min

Strategy Pattern Structure: The Class Diagram

A Context holds a Strategy, and each ConcreteStrategy is one interchangeable algorithm.

Strategy has three participants and a client: the interface every algorithm shares, the classes that implement it, and the context that holds one of them and calls it. This card reads their roles off the Gang of Four's class diagram, then sets out who chooses the strategy and how the context passes it what it needs.

Strategy participants
Each participant and its role
ParticipantRole
StrategyDeclares the one operation every algorithm in the family provides, such as execute.
ConcreteStrategyImplements that operation one way. There is one class per algorithm.
ContextHolds a reference to a strategy and calls it to do the varying part of its work. It knows only the interface.
ClientCreates the concrete strategy it wants and hands it to the context, at construction or through setStrategy.

The hollow diamond says the context has a strategy that was made elsewhere: the client creates it, and the context receives it. So the decision about which algorithm to use sits with the client, and the context runs whichever arrives without a single branch on its type.

The context and the strategy must agree on what data passes between them. Either the context passes everything an algorithm could need as arguments to execute, or it passes itself so the strategy can ask for what it needs. Arguments keep the strategy independent of the context, and are the usual choice; passing the context suits algorithms that need different data from it.

Because the context holds the strategy as a field, the client can replace it at any time. A checkout can switch from standard to express shipping without being rebuilt, and a test can hand the context a strategy that returns a fixed value.