Command pattern, which is the pattern of commands, wraps a command in an object, passes the command object to the executor of the command, and belongs to the design pattern of the behavior class.
Here is a simple case of the command pattern.
The Stock represents the object being manipulated. The order defines the interface of the command, BuyStock, Sellstock is the concrete class that implements the order interface. The Broker is the executor of the command. Commandpatterndemo demonstrates the command mode.
Code implementation
Order, Command interface
Public Interface Order { publicvoid execute ();}
The specific command class
Public class Implements Order { private stock stock; Public BuyStock (stock stock) { this. Stock= stock; } @Override publicvoid execute () { stock.buy (); }}
Public class Implements Order { private stock stock; Public Sellstock (stock stock) { this. Stock= stock; } @Override publicvoid execute () { Stock.sell (); }}
Broker, Performer of command
Importjava.util.LinkedList;Importjava.util.List; Public classBroker {Privatelist<order> orders =NewLinkedlist<>(); Public voidTakeorder (Order order) {Orders.add (order); } Public voidplaceorders () { for(Order order:orders) {order.execute (); } }}
Demo Command mode
Public class Commandpatterndemo { publicstaticvoid main () { new Stock ("Apple", +); New BuyStock (stock); New Sellstock (stock); New Broker (); Broker.takeorder (buystock); Broker.takeorder (sellstock); Broker.placeorders (); }}
Consider extensibility
When you need to add a command operation, such as Freezestock:
1. Add a file to implement the Freezestock class so that it implements the Order interface.
2. Add the Freeze method to the Stock
3. Call the new Freezestock object in the client, class implementation command.
You can achieve the effect of new operations without modifying the code of the command executor Broker.
Resources
Design Patterns-command Pattern, Tutorialspoint
[Design Pattern] Command Pattern Simple Case