Preliminary Research on the Design Mode-command mode

Source: Internet
Author: User

COMMAND, also known as Action, and Transaction, encapsulate a request as an object so that you can parameterize the customer with different requests, queues or records request logs, and supports unrecoverable operations. The command mode can completely decouple the request sender and receiver. There is no direct reference relationship between the sender and receiver. The object sending the request only needs to know how to send the request, instead of how to complete the request.

I. Application scenarios

1. When you need to abstract the actions to be executed to parameterize an object. This parameterization mechanism is implemented through callback function expressions in the process language, while the Command mode is an object-oriented alternative to the callback mechanism.

2. Specify, arrange, and execute requests at different times. A Command object can have a lifetime unrelated to the initial request. You can pass the requested Command object to another different process and implement the request there.

3. Cancel the operation. Store the status in a history list before executing the Command execute operation, by traversing the list backward and forward, and calling the undo and redo methods respectively, the undo and redo methods are not limited to the number of "undo" and "redo" operations ".

4. Log modification is supported. It can be used to redo modifications when the system crashes to restore the status before the crash. You can add loading and storage operations to the Command interface to persist system modifications to log files. For system recovery, you only need to read the modification records from the log file, and then run the Command execute Command again.

5. construct a system using high-level operations built on primitive operations, such as information systems that support transactions. A transaction encapsulates a group of changes to the data. The Command mode provides a method to model the transaction. The common interfaces provided by Command can be used to call all transactions in a consistent manner. In addition, the command mode is easy to add new transactions to expand the system.

Ii. UML diagram


Note: The Key to the command mode is to introduce the abstract command class. The request sender program the abstract command class. Only specific commands that implement the abstract command class are associated with the request receiver.

Iii. Java implementation

Package study. patterns. command; import java. util. arrayList; import java. util. list;/*** the essence of the command mode is to encapsulate the request. A request corresponds to a command, which separates the responsibility for issuing the command from the responsibility for executing the command. * Each Command is an operation: the Requesting Party sends a request and requires an operation. The receiving party receives the request and performs the corresponding operation. * The command mode allows the requester and receiver to be independent, so that the requester does not have to know the interfaces of the receiver, * You do not need to know how the request is received, whether the operation is executed, when it is executed, and how it is executed. * @ Author qbg */public class CommandPattern {public static void main (String [] args) {// The request receiver (ReceiverA) is encapsulated into a specific command object (ConcreteCommandA, separated from the request sender (CommandPattern. Command comA = new ConcreteCommandA (); Command comB = new ConcreteCommandB (); Command macro = new macrocommand(;;macro.addcommand(coma;;macro.addcommand(combate+macro.exe cute (); macro. undo (); macro. redo (); macro. writeLog ("config. log "); macro. readLog ("config. log ") ;}}/*** abstract command: Use the combination mode to implement macro commands (similar to batch commands, You can execute a batch of commands) */interface Command {/*** add command (combination mode) * @ param Command */public void addCommand (command Command);/*** DELETE command (Combination Mode) * @ param command */public void removeCommand (Command command);/*** undo (undo last operation) */public void undo (); /*** redo (redo last operation) */public void redo ();/*** execute Command */public void execute (); /*** read and execute the command from the specified file to be re-executed * @ param fileName */public void readLog (String fileName ); /*** Save the executed command to the file for disaster recovery * @ param fileName */public void writeLog (String fileName);}/*** default implementation class, no implementation */class DefaultCommand implements Command {@ Overridepublic void addCommand (Command command) {throw new IllegalAccessError ("method not implemented");} @ Overridepublic void removeCommand (Command command Command) {throw new IllegalAccessError ("method not implemented") ;}@ Overridepublic void undo () {throw new IllegalAccessError ("method not implemented") ;}@ Overridepublic void redo () {throw new IllegalAccessError ("method not implemented") ;}@ Overridepublic void execute () {throw new IllegalAccessError ("method not implemented") ;}@ Overridepublic void readLog (String fileName) {throw new IllegalAccessError ("method not implemented") ;}@ Overridepublic void writeLog (String fileName) {throw new IllegalAccessError ("method not implemented ");}} /*** command receiver A, specific service processing */class ReceiverA {public void action () {System. out. println ("ReceiverA: do something .... ") ;}}/*** command receiver B, specific service processing */class ReceiverB {public void action () {System. out. println ("ReceiverB: do something .... ") ;}}/*** specific command implementation, overwrite the default command class execute () */class ConcreteCommandA extends DefaultCommand {private ReceiverA receiver = new ReceiverA (); @ Overridepublic void execute () {assumer. action () ;}@ Overridepublic String toString () {return "ConcreteCommandA" ;}}/*** specific command implementation, overwrite the execute () of the default command class () */class ConcreteCommandB extends DefaultCommand {private ReceiverB receiver ER = new ReceiverB (); @ Overridepublic void execute () {receiver er. action () ;}@ Overridepublic String toString () {return "ConcreteCommandB" ;}}/*** macro command: Use the combination mode and command mode, batch Execute Command */class MacroCommand implements Command {private ListCommands = new ArrayList(); @ Overridepublic void addCommand (Command command) {this. commands. add (command) ;}@ Overridepublic void removeCommand (Command command) {this. commands. remove (command);}/*** in addition to Undo through a reverse operation, you can also save the historical state of the object to Undo it, * the latter can be implemented using the Memento Pattern. * // @ Overridepublic void undo () {if (commands. size ()> 0) {System. out. println ("undo command:" + commands. get (commands. size ()-1) ;}@overridepublic void redo () {if (commands. size ()> 0) {System. out. println ("redo command:" + commands. get (commands. size ()-1); }}@ Overridepublic void execute () {for (Command com: commands00000000com.exe cute () ;}/ *** the serialization process is omitted, command must implement java. io. serializable interface. * // @ Overridepublic void readLog (String fileName) {System. out. println ("From log file:" + fileName + "load command list... ");}/*** the deserialization process is omitted. It is only used to indicate that the command mode can record the command log file. * // @ Overridepublic void writeLog (String fileName) {System. out. println ("persistence command list:" + commands + "to log file:" + fileName );}}
Running result:

ReceiverA: do something .... receiverB: do something .... undo command: ConcreteCommandB redo command: ConcreteCommandB persistence command list: [ConcreteCommandA, ConcreteCommandB] to log file: config. log from log file: config. load command list in log...

Iv. Advantages and Disadvantages

Advantages:

1. Reduce system coupling. The Command mode decouples the called object from the object that knows how to implement the operation.

2. It is easy to add new commands without changing the existing classes, which is highly scalable.

3. Multiple commands can be assembled into a composite command (macro command ).

4. A design and implementation scheme is provided for Undo and Redo requests.

Disadvantages:

1. for complex systems, a large number of specific command classes may be generated.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.