Java Design Pattern cainiao series (7) Command pattern modeling and implementation
Command: encapsulate a request (Command/password) as an object to parameterize the object using different requests, queues, or logs. The command mode also supports the Undo operation. The purpose of the command mode is to decouple the sender and executor of the command and separate the request and execution.
I. uml modeling
Ii. Code implementation:
/*** Example: Take a meal at a restaurant as an example. There are three steps ** 1, here is a kung pao chicken ding --> the customer issued a password ** 2. The customer gave me a copy of kung pao chicken ding. Then the command is passed to the cook. --> The password is passed to the cook ** 3. Then the cook starts to cook kung pao chicken. --> The cook executes the command according to the password **. From these three steps, we can see that kung pao chicken Ding is delivered to others instead of me if I want to eat it. ** What I want is a result-the kung pao chicken dish is ready, and I don't have to worry about how it is made. */Interface Command {/*** password execution */public void execute ();/*** password revocation */public void undo ();} /*** password -- passed by the second user */class OrderCommand implements Command {private cookizer er cook; public OrderCommand (cookizer er cook) {this. cook = cook;} @ Overridepublic void execute () {cook. cooking () ;}@ Overridepublic void undo () {cook. unCooking () ;}}/*** cook -- real password performer */class cookcycler {public void cooking () {System. o Ut. println (I started to stir-fry chicken with kung pao ...);} public void unCooking () {System. out. println (do not stir-fry chicken diced with kung pao ...);}} /*** Customer -- real password sender */class Customer {private Command command Command; public Customer (command Command) {this. command = command;}/*** separate command issuance and execution */public void order () using command.exe cute ();} public void unOrder () {command. undo () ;}/ *** client Test class ** @ author Leo */public class Test {public static void main (String [] args) {/***, etc. The executor waiting for the password-there must be a cook for cooking. */cookcycler runner ER = new cookcycler ();/*** wait for the password to be sent to the cook-because the customer does not know what food to ask, but the password must always be passed to the cook's ears. */Command cmd = new OrderCommand (cmder); Customer customer = new Customer (cmd);/*** execution password */customer. order ();/*** undo password */customer. unOrder ();}}
Iii. application scenarios
Restaurant ordering, remote control, queue request, and log request.
Iv. Summary
From the above example, we can see that the command mode decouples the "Action requestor" from the "action performer" object, which is the benefit of encapsulating method calls.