Design Pattern-Command pattern

Source: Internet
Author: User
Design Pattern-Command pattern(22:52:40)
Tags: Follow the torch to see the Chinese design pattern Command pattern Java Chen Baofeng it Category: Design Model

The command mode is a group of behavior modes in the design mode group. The core of the command mode is to standardize and abstract multiple calls between modules. It is hard to imagine using the command name, the so-called command mode should be similar to the process of issuing commands by superiors and lower-level personnel. Let's assume that a lead is abroad, he needs to send different work requirements (called commands) like different departments. Then, if he does not have a convenient communication tool, he can only send his requirements through letters, then he will write a letter to the requirements of different departments, so that all commands share the characteristics of the letter, and the postman does not know what the content of the letter is, his task is only responsible for delivering commands, and the owner of each department knows how to open this letter and the task requirements expressed in the execution letter. We abstract such a similar problem into the command mode we mentioned here.

Let's take a look at the common problems of the command mode, such:

A library management system may need to perform different actions. In the case of some errors, you may need to cancel some actions, or re-execute an action, so how can we use a simple method to build actions and organize their calls? This problem is suitable for solving the problem using the command mode.

We are used to indicate the situation described above:

Let's sum up, what kind of problems need the command mode?

When you need to separate the client code from the execution process of how to execute an action, the problem requirements are as follows:

1. A simple method is required to dynamically add new actions or modify existing actions.

2. Keep the client code concise.

3. The client does not need to know the details of a specific requirement.

4. The interface defined for execution of specific requirements should be simple.

5. You can easily cancel the current action or repeat the previous action.

6. These actions can be conveniently executed synchronously, remotely called, or called in different threads.

When you encounter the above problem, you need to think of the command mode. Here we will describe the method to solve the above problem in the command mode:

1. First, we abstract all command calling processes into an interface called command, which defines a call method called execute.

2. Design every action to be executed into a class so that the class can implement the command interface and implement the execute method defined in the interface.

3. When the client needs to execute a specific command, the client creates a specific command object (for example, specificcommand) and then passes the object to a caller object (for example, invoker ).

4. For the caller object (invoker), it does not need to know the details of a specific command. Its task is simply to call the execute method of the command object.

The above problem description is not difficult for the program developers to understand, but it will be clearer and more accurate to express it in graphics, therefore, we use the following UML diagram to express the specific process:

 

Through the graphic description above, you should have a comprehensive grasp of the problem solving process in the command mode. Now we will describe some rules of the command mode when solving the problem, let you know what you need to pay attention to when solving the problem, and you can design code more smoothly and rigorously:

1. specificcommand can contain command-related status data.

2. specificcommand can be used to implement a specific action or call other objects to complete the work.

3. The command interface can contain an undo method when appropriate to complete the command revocation action.

4. You can call command objects in a separate thread, process, or client to call the server.

5. You can call commands in queue to achieve synchronization.

These points of attention and experience deserve your attention when designing the command mode.

 

After such a theoretical analysis, what we need is practice. As I mentioned earlier, the book management system is used as an example to illustrate how this system performs different actions, how can we use the command mode to implement the action commands of such a library management system?

Suppose there is a class called librarycommandinvoker class that is responsible for calling the command. Just like the postman we mentioned earlier, his task is only responsible for calling the command, regardless of the specific implementation of the command, the class of the client is called client. It is responsible for constructing the objects of various commands to be executed, and then calling librarycommandinvoker to execute the command object. Different command classes implement the same abstract interface called command. Assume that there are three specific commands: checkoutcommand, checkincommand, and putonholdcommand, let's take a full look at the working process of this command mode through a UML design drawing:

 

Through the above figure, I believe you have a more detailed understanding of the command mode, and now we can easily understand, the core of the command mode is to design various call requirements passed between the caller and the called into commands. Abstract command interfaces are used to unify the features of different commands. by designing a caller object such as librarycommandinvoker, the calling methods and processes of commands are unified. In this way, the complexity of command execution can be simplified, in practice, especially for remote calls to the network, this command mode will greatly simplify the complex program of network communication programs.
In order to better describe the command mode, we take the command execution process of adding books in the library management system as an example to illustrate the specific implementation through the actual source code.

This function includes the following content:

Command: the common specification of all commands. It is an interface;

Addbookcommand: a specific command class that completes the command process for adding books;

Commandinvoker: A Tool class used to call command objects;

Client: a client class that generates and calls command objects;

 

 

 

The command code is as follows:

Public interface command {

Public void execute ();

}

The code for addbookcommand is as follows:

Public class addbookcommand implements command {

Private book;

Public addbookcommand (Book ){

This. Book = book;

}

Public void execute (){

// Connect to the database

Connection con = ...;

String SQL = "insert into books values (?, ?, ?) ";

// Get the preparedstatment object

PSTA = con. preparestament (SQL );

PSTA. setstring (1, Book. GETID ());

PSTA. setstring (2, Book. getname ());

PSTA. setdouble (3, Book. getprice ());

Psta.exe cuteupdate ();

......

}

}

 

The commandinvoker code is as follows:

Public class commandinvoker {

Public void invok (command cmd ){

Cmd.exe cute ();

}

}

 

The client code is as follows:

Public class client {

Public static void main (string ARGs []) {

Book = New Book ("id00231", "Java", 128 );

Command cmd = new addbookcommand (book );

Commandinvoker CI = new commandinvoker ();

CI. invok (CMD );

}

}

 

Now we have read a simple example code. Let's summarize the advantages and disadvantages of the command mode in the above several forms?

The command mode has the following advantages:

Reduces the call logic responsibility;

Provides convenience for function expansion;

It can easily provide the Undo function for various commands;

You can also put multiple commands in one queue for unified execution (we didn't provide specific code before, you can consider how to implement such requirements ?);

Commands can be run in independent threads or remotely;

 

There are also some unfavorable factors:

Added System overhead for object creation, use, and extinction;

The structural accountability of the application itself has increased;

 

We have finished talking about the command mode content. I hope you can put it into practice and improve the design philosophy of the program.

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.