Use the Strategy pattern when you want to use different variants of an algorithm within an object and be able to switch from one algorithm to another during runtime. Use the Strategy when you have a lot of similar classes that only differ in the way they execute some behavior.
The command pattern should be used when: You need a command to have a life span independent of the original request, or if you want to queue, specify and execute requests at different times. You need undo/redo operations. The command's execution can be stored for reversing its effects.
In fact the two can be used together. For example, you may have a factory that creates your business objects.
Strategy pattern is also known as Policy Pattern. We define multiple algorithms and let client application pass the algorithm to be used as a parameter. One of the best example of strategy pattern is Collections.sort() method that takes Comparator parameter.
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.
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.
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.
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 might be wrong in my opinion, but I treat the command as function-to-execute, or reaction. There should be at least two players: the one who requests the action, and the one who executes the action. GUI is typical example for command pattern:
The command is usually bounded to some scope or business area, but not necessary: you may have commands that issue a bill, start a rocket or remove a file implementing the same interface (e.g. single execute()
method) within one application. Often commands are self-containing, so they don't need anything from the executor to process the task they are intend to (all necessary information is given at construction time), sometimes commands are context-sensitive and should be able to discover this context (Backspace command should know the caret position in the text to correctly remove the previous character; Rollback command should discover the current transaction to rollback; ...).
The strategy is a bit different: it is more bound to some area. The strategy may define a rule to format a date (in UTC? locale specific?) ("date formatter" strategy) or to calculate a square for a geometric figure ("square calculator" strategy). Strategies are in this sense flyweight objects, that take something as input ("date", "figure", ...) and make some decision on its basis. Perhaps not the best, but good example of strategy is one connected with javax.xml.transform.Source
interface: depending on whether the passed object is DOMSource
or SAXSource
or StreamSource
the strategy (= XSLT transformer in this case) will apply different rules to process it. The implementation can be a simple switch
or involve Chain of responsibility pattern.
But indeed there is something in common between these two patterns: commands and strategies encapsulate algorithms within the same semantic area.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With