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