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