Card 02/ 05
Command vs Strategy
Both are an object with one method; one says what to do, the other says how.
Command and Strategy are both an object with one main method, passed to another object that calls it, and they are told apart by what that method stands for. A command is a request: something to be done, often later, perhaps queued, logged or undone. A strategy is a way of doing a job the receiver is already doing now. This card compares the two, then uses one discount class both ways.
| Question | Command | Strategy |
|---|---|---|
| What does the object stand for? | A request | An algorithm |
| When does it run? | Later, or more than once, or never | Now, as part of the receiver's own work |
| What else can be done with it? | Queued, logged, undone or retried | Swapped for another of the same kind |
| Does the receiver know what it does? | No; it calls execute and moves on | It knows the job, and delegates how to do it |
| What does a set of them look like? | A history, or a queue of requests | A menu of interchangeable choices |
As a strategyhow the checkout prices, now
checkout = Checkout(pricing=TenPercentOff())
checkout.total(basket)The checkout asks the strategy how to compute the total, and uses the answer straight away.
As a commanda request to change the basket, kept
apply = ApplyDiscount(basket, TenPercentOff())
history.run(apply)
history.undo()The request is an object in a history, so it can be undone.
The deciding question is whether the object would make sense in a list kept for later. A history of commands is natural: each is something that happened. A history of strategies is not: each is a way of doing a job, and the list would say nothing about what was done.
The contrast shows the two together, too: the command holds a strategy. That is common, and it is why the method count settles nothing. Name each object by what it stands for.
← → move through sections and cards