Java/android Design Mode Learning Note (+)---command mode

Source: Internet
Author: User

In this blog we introduce the command pattern, which is one of the behavioral design patterns. Command mode is more flexible than other design patterns, we touch a lot of command mode example is the program menu commands, such as in the operating system, we click the Shutdown command, the system will perform a series of operations, such as first pause processing events, save some configuration of the system, and then end the program process, Finally call the kernel command shut down the computer, and so on, for this series of commands, the user does not have to pipe, the user just click the system's Shutdown button to complete a series of commands. And our command pattern is actually the same, a series of method calls encapsulated, the user only need to call a method to execute, then all of these encapsulated methods will be executed in one call.
Reprint Please specify source: http://blog.csdn.net/self_study/article/details/52091539.
PS: The technology is interested in the same shoe plus group 5,446,459,721 Exchange.

Total catalog of design patterns

Java/android design mode Learning Notes directory

features

  encapsulates a request into an object that allows the user to parameterize the client with different requests, queue requests or log requests, and support revocable operations.
Usage Scenarios for Command mode:

    • It is necessary to abstract the action to be executed and provide it in the form of parameters-similar to the callback mechanism in the process design, and the command pattern is an object-oriented substitute of the callback mechanism;
    • Specifying, arranging, and executing requests at different times, a command object can have lifetimes unrelated to the initial request;
    • Need to support cancel operation;
    • Support to modify the log function, so that when the system crashes, these changes can be re-done again;
    • Need to support transactional operations;
    • The system needs to combine a set of operations that support macro commands.
Specific usage scenarios listed on the wiki:
  • GUI buttons and menu items
  • In the Java Swing and Delphi language, an action is a command that, in addition to executing a predetermined command, may have an associated icon, keyboard shortcut, bubble hint text, and so on. An element of a toolbar button or menu may be initialized entirely with an Action object.
  • Macro Recording
  • If all the user actions represent a command object, then a program can easily save a series of command objects, and then be able to re-execute the series of commands to implement a callback action. If the script engine is embedded in the program, then each command object can implement the Toscript () method, and the user's action can be easily saved as a script object.
  • Mobile Code
  • Similar to Java, a language that can transfer code from one place to another through urlclassloders, and commands in the code base enable new behavior to be passed to a remote location (EJB command,master worker mode).
  • Multi-level undo
  • If all the user actions in the program are implemented as command objects, the program can save the most recently executed command object, and when the user wants to undo some of the commands, the program can simply pop out the nearest command and execute his undo method.
  • Networking
  • The ability to transfer all the command objects over the network to another device, such as user operations in the end of the tour.
  • Parallel processing
  • All commands are written as tasks in the shared resource and are concurrently executed by many threads (this variant on the remote machine may be called Master/worker mode).
  • Progress bars
  • We assume that the program has a series of commands that need to be executed sequentially, and if each command object has a getestimatedduration () method, then the program can easily estimate the overall execution time and then show a meaningful progress bar to reflect how much of the current task is executing.
  • Thread Pools
  • A representative thread pool may have a public addtask () method used to add a work task to the internal wait queue, in which a series of threads are used to execute a series of command objects in the queue. In general, these objects implement a common interface, such as Runnable, to allow the thread pool to execute these commands, although the thread pool class does not know that it will be used to handle specific tasks.
  • Transactional behavior
  • Similar to the undo operation, a database engine or software installer may maintain a list of operations that have been executed or will be executed, and if one fails, all others will be restored or discarded (often referred to as rollback, rollback). For example, if the associated two database tables must be updated, and the second update fails, the transaction will be rolled back, so the first table update will be discarded.
  • Wizards
  • A wizard page is a page configuration page that users pop up when they click on the last page of the "End" button (configure user habits, etc.), in which case a common way to separate user action code from program code is to use Command objects to implement wizard functions. This command object is created the first time the wizard page is displayed, and each wizard page saves its own GUI changes in a command object, so this object is positioned as a further action by the user. The "End" action simply triggers a excete () action so that the command class will achieve the desired effect.

UML class Diagram

Let's take a look at the UML class diagram of the command pattern:
  
Description of the role of the command pattern:

    • Receiver: Receiver Role
    • This class is responsible for specific implementation or implementation of a request, the popular point is that the role of the implementation of specific logic, in the above mentioned "shutdown" action command, as an example, its receiver role is to actually execute the various shutdown logic of the underlying code. Any class can be a receiver, and the method that encapsulates the specific operational logic in the receiver class is called the action method;
    • Command: Commands interface
    • An abstract interface that defines the basic behavior of all specific command classes;
    • Conretecommand: Specific command role
    • This class implements the command interface, which invokes the relevant methods of the receiver role in the Execute method, weakly coupling between the receiver and the specific behavior of the command execution. And execute is often called the execution method, such as the above mentioned "shutdown" operation implementation, may also contain a lot of related operations, such as saving data, closing the file, end the process, etc., if the specific logical processing of these columns as a receiver, then the method of invoking these specific logic can be regarded as the execution method;
    • Invoker: Requestor role
    • The function of the class is to invoke the Command object to execute the specific request, the related method we call the action method, "shut down" command for example, the shutdown command generally corresponds to a shutdown method, the execution of the shutdown command is equivalent to the shutdown method to execute the specific logic, this shutdown method can be regarded as the requestor;
    • Client: Clients role
Thus we can write the general code of the command pattern:
Receiver.class Specific Logic performer

publicclass Receiver {    publicvoidaction() {        System.out.print("执行具体的操作");    }}

Command.class abstract Command class

publicinterface Command {    void execute();}

Concretecommand.clas specific Command classes

publicclass ConcreteCommand implements Command {    private Receiver receiver;    publicConcreteCommand(Receiver receiver) {        this.receiver = receiver;    }    @Override    publicvoidexecute() {        receiver.action();    }}

Invoker.class Requestor

publicclass Invoker {    private Command command;    publicInvoker(Command command) {        this.command = command;    }    publicvoidaction() {        command.execute();    }}

Client clients

publicclass Client {    publicstaticvoidmain(String[] args) {        new Receiver();        new ConcreteCommand(receiver);        new Invoker(command);        invoker.action();    }}

Finally, it is possible to invoke the real Receiver execution logic through the Invoker class.

Example and source code

This is an example of a simple control of the light-off and gate-switch scenarios:
Light.class and Door.class Actual control classes

public   Class  Light {public  void  lighton  () {system.    Out . Print (); } public  void   Lightoff  () {system.    Out . Print (); }}
publicclass Door {    publicvoiddoorOpen() {        System.out.print("door open\n");    }    publicvoiddoorClose() {        System.out.print("door close\n");    }}

Then there is the control class of the electric Light:
Lightoncommand.class and Lightoffcommand.class

public   class   lightoncommand  implements  command     { public  light Light; public  lightoncommand  (light)    {this . Light = light; }  @Override  public  void  execute  () {Light.lighton (); }}
publicclass LightOffCommand implements Command{    public Light light;    publicLightOffCommand(Light light) {        this.light = light;    }    @Override    publicvoidexecute() {        light.lightOff();    }}

Related control classes for doors:
Dooropencommand.class and Doorclosecommand.class

public   class  dooropencommand  implements  command     { public  Door Door; public  dooropencommand  (Door Door)    {this . Door = door; }  @Override  public  void  execute  () {door.dooropen (); }}
publicclass DoorCloseCommand implements Command{    public Door door;    publicDoorCloseCommand(Door door) {        this.door = door;    }    @Override    publicvoidexecute() {        door.doorClose();    }}

Then there is a no-action default command class:
Nocommand.class

publicclass NoCommand implements Command{    @Override    publicvoidexecute() {    }}

Finally, the control class:
Controller.class

 Public classController {PrivateCommand[] Oncommands;PrivateCommand[] Offcommands; Public Controller() {oncommands =Newcommand[2]; Offcommands =Newcommand[2]; Command Nocommand =NewNocommand (); oncommands[0] = Nocommand; oncommands[1] = Nocommand; offcommands[0] = Nocommand; offcommands[1] = Nocommand; } Public void SetCommand(intSlot, command OnCommand, command Offcommand) {Oncommands[slot] = OnCommand;    Offcommands[slot] = Offcommand; } Public void OnCommand(intSlot) {Oncommands[slot].execute (); } Public void Offcommand(intSlot) {Offcommands[slot].execute (); }}

Test code

Light light =NewLight ();D oor Door =NewDoor (); Lightoncommand Lightoncommand =NewLightoncommand (light); Lightoffcommand Lightoffcommand =NewLightoffcommand (Light);D Ooropencommand Dooropencommand =NewDooropencommand (door);D Oorclosecommand Doorclosecommand =NewDoorclosecommand (door); Controller Controller =NewController (); Controller.setcommand (0, Lightoncommand, Lightoffcommand); Controller.setcommand (1, Dooropencommand, Doorclosecommand); Controller.oncommand (0); Controller.offcommand (0); Controller.oncommand (1); Controller.offcommand (1);

Results:

This realizes the light and Door control, in fact, this example is only to achieve the basic framework of the command mode, the use of command mode is in fact its log and rollback undo function, each time the command is executed by printing the corresponding key log, Or, after each execution, save the command in the list and each command implements an undo method so that it can be rolled back. Alternatively, you can construct a Macrocommand macro command class to execute several related commands sequentially. Of course, the space can be divergent a lot, interested can be realized by themselves, the principle is the same.

Summary

The command mode decouples the requested object from the object executing the request, and the decoupling is communicated through the Command object, and the caller sends the request through execute of the command object, which causes the receiver's action to be invoked, and the caller can accept the command as a parameter or even dynamically at run time. The command can support revocation by implementing an Undo method to return to the state before execute was executed. The Macrocommand macro command class is a simple extension of a command that allows multiple commands to be invoked, and a macro method can also support revocation. The log system and transaction system can be implemented in command mode.
The advantages of the command pattern are obvious, decoupling between the caller and performer, more flexible control, and better extensibility. The disadvantage is more obvious, is the explosion of the class, the creation of a large number of derivative classes, which is the majority of design patterns of the "common problem" is a no way to avoid problems.

Source Download

Https://github.com/zhaozepeng/Design-Patterns/tree/master/CommandPattern

References

Https://en.wikipedia.org/wiki/Command_pattern
http://blog.csdn.net/jason0539/article/details/45110355

Java/android Design Mode Learning Note (+)---command mode

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.