Both design patterns encapsulate an algorithm and decouple implementation details from their calling classes. The only difference I can discern is that the Strategy pattern
Strategies encapsulate algorithms. Commands separate the sender from the receiver of a request, they turn a request into an object.
If it's an algorithm, how something will be done, use a Strategy. If you need to separate the call of a method from its execution use a Command. Commands are often used when you queue up messages for later use, like a task or a transaction.
The way that I look at it is that you have multiple ways of doing the same thing, each of those is a strategy, and something at runtime determines which strategy gets executed.
Maybe first try StrategyOne, if the results aren't good enough, try StrategyTwo...
Commands are bound to distinct things that need to happen like TryToWalkAcrossTheRoomCommand. This command will be fired whenever some object should try to walk across the room, but inside it, it might try StrategyOne and StrategyTwo for trying to walk across the room.
Mark
I'm including an encapsulation hierarchy table of several of the GoF design patterns to help explain the differences between these two patterns. Hopefully it better illustrates what each encapsulates so my explanation makes more sense.
First off, the hierarchy lists the scope for which a given pattern is applicable, or the appropriate pattern to use to encapsulate some level of detail, depending on which side of the table you start at.
As you can see from the table, a Strategy Pattern object hides details of an algorithm's implementation, so the use of a different strategy object will perform the same functionality but in a different way. Each strategy object might be optimized for a particular factor or operate on some other parameter; and, through the use of a common interface, the context can safely work with either.
The Command Pattern encapsulates a much smaller level of detail than an algorithm. It encodes the details needed to send a message to an object: receiver, selector and arguments. The benefit to objectifying such a tiny part of the process execution is that such messages can be invoked along different points of time or location in a general way without having to hard-code its details. It allows messages to be invoked one or more times, or passed along to different parts of the system or multiple systems without requiring the details of a specific invocation to be known before execution.
As is typical for design patterns, they do not require all implementations to be identical in detail to bear the pattern name. Details can vary in implementation and in what data is encoded in the object versus as method arguments.
Command:
Basic components:
execute()
Workflow:
Client calls Invoker => Invoker calls ConcreteCommand => ConcreteCommand calls Receiver method, which implements abstract Command method.
Advantage : Client is not impacted changes in Command and Receiver. Invoker provide loose coupling between Client and Receiver. You can run multiple commands with same Invoker.
Command pattern allows you to execute a command on different Receivers by using same Invoker. Invoker is unaware of type of Receiver
For better understanding of concepts, have a look at this JournalDev article by Pankaj Kumar and dzone article by James Sugrue in addition to Wikipedia link.
You can use Command pattern to
Decouple the invoker & receiver of command
Implement callback mechanism
Implement undo and redo functionality
Maintain a history of commands
java.lang.Thread
is one good implementation of Command pattern. You can treat Thread as invoker & class implementing Runnable as ConcreteCommonad/Receiver and run()
method as Command.
Undo/Redo version of command pattern can be read at Theodore Norvell's article
Strategy:
Strategy pattern is very simple to understand. Use this pattern when
You have multiple implementations for an algorithm and implementation of algorithm can change at run time depending on particular conditions.
Take an example of Airline booking system's Fare component
Airlines would like to offer different Fares during different time periods - Peak and Off Peak months. During Off peak travel days, it would like to stimulate the demand by offering attractive discounts.
Key takeaways of Strategy pattern:
Related posts with code examples:
Using Command Design pattern
Real World Example of the Strategy Pattern
For me, the difference is one of intent. The implementations of both patterns are pretty similar, but have different purposes:
For a Strategy, the component using the object knows what the object does (and will use it to perform a part of its own work), but it doesn't care how it does it.
For a Command, the component using the object knows neither what the Command does nor how it does it - it just knows how to invoke it. The caller's task is just to run the command - the processing carried out by the Command doesn't form part of the caller's core work.
This is the difference - does the object using the component actually know or care about what the component does? Most of the time this can be determined based on whether the pattern object returns a value to its invoker. If the invoker cares about what the pattern object does then it will probably want it to return something and it will be a Strategy. If it doesn't care about any return value it is probably a Command (note, something like a Java Callable is still a Command because, although it returns a value, the caller doesn't care about the value - it just passes it back to whatever originally supplied the Command).
Answering a very old question. (is anybody seeing lastest answers instead of most voted?)
It is a valid confusion to have because of the similarities. Both Strategy and Command patterns utilize encapsulation. But that does not make them same.
The key difference is to understand what is encapsulated. The OO principle, both patterns depend on, is Encapsulate what varies.
In case of strategy, what varies is algorithm. For example, one strategy object knows how to output to XML file, while the other outputs to, say, JSON. Different algorithms are kept (encapsulated) in different classes. It is as simple as that.
In case of command, what varies is the request itself. Request may come from File Menu > Delete
or Right Click > Context Menu > Delete
or Just Delete Button pressed
. All three cases can generate 3 command objects of same type. These command objects only represent 3 requests for deletion; not deletion algorithm. Since requests are bunch of objects now, we could manage them easily. Suddenly it become trivial to provide functionality such as undo or redo.
It doesn't matter how command implements the requested logic. On calling execute(), it may implement an algorithm to trigger deletion or it can even delegate it to other objects, may even delegate to a strategy. It is only implementation detail of the command pattern. This is why it is named as command though it is not a polite way to request :--)
Contrast it with strategy; this pattern is only concerned with the actual logic that gets executed. If we do that, it helps to achieve different combinations of behaviors with minimal set of classes, thus preventing class explosion.
I think, Command helps us to broaden our understanding of encapsulation while Strategy provides natural use of encapsulation and polymorphism.