Card 02/ 05

ComparisonDifficulty: Intermediate2 min

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.

Command and Strategy side by side
QuestionCommandStrategy
What does the object stand for?A requestAn algorithm
When does it run?Later, or more than once, or neverNow, as part of the receiver's own work
What else can be done with it?Queued, logged, undone or retriedSwapped for another of the same kind
Does the receiver know what it does?No; it calls execute and moves onIt knows the job, and delegates how to do it
What does a set of them look like?A history, or a queue of requestsA menu of interchangeable choices
One discount, used as a strategy and as a command

As a strategyhow the checkout prices, now

py
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

py
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.