For example, in command pattern

Source: Internet
Author: User

Add in front

When it comes to orders, most people think of the following picture in their minds.

 

This is a caricature in real life, the decision-making people do not know what the characteristics of the people who run the decision, backseat, layman leadership experts say this is the case. Only in the field of software design, we obviously have to justify this phenomenon, so that the Lion King can remember all the characteristics of their subordinates and directly call to inform the task. Obviously he was embarrassed, and the leaders were very busy. This is the work of the Secretariat. The Lion King merely instructed "the recent prevalence of rat infestation." It's time for the secretaries to draft red-headed (orders) and send them to the relevant operating departments (CATS) to improve their performance, to separate the published request (the secretariat) from the running request (CAT) and to encapsulate the behavior (the mouse) into objects (red-headed), which is the command pattern.

Official definition

Encapsulates a request into an object so that a different request can be used to account for the customer, to queue the request, to log the request logs, and to run the revocable operation--gof23.

Encapsulates the request as an object, which is the command object. In a structured program. Requests are generally expressed in the form of functions. For a running object that might be involved in the request, let's say we pass it as a letter, which causes the following problems

1) Tight coupling. Client programs need to rely on the running object, in the above example, the upper layer in the announcement of the command to rely on the detailed subordinates, which will violate the dependency inversion principle, the request is encapsulated as a command object, these command objects follow the common Command interface, which overcomes the high-level dependency problem.

2) The function does not emphasize the undo operation, which requires additional business logic in the function to save the state of the object.

3) The reusability and extension of the function is poor, which is the reason why the structure is gradually replaced by the object language.

Different requests can be used to account for the customer, which is similar to the dynamic setting algorithm of the policy mode. In the example above. Different requests are encapsulated into different commands. The user is free to choose which command is currently running.

The programming principle of "interface-oriented rather than implementation" enables you to select verbose commands at run time, depending on context. For example, the Lion King is not the sum of mice, this period of time organs work style is poor, late phenomenon frequent. The Lion King will instruct "multi-crowing, grasping four winds", then the secretariat will draft the crowing document and ensure that it can be issued to run. The role of the Secretariat, in fact, is like a trigger invoker (remote control), what kind of file they draft and run, which is equivalent to what kind of command object the trigger binds to. This binding relationship is determined by the client (Lion King).

Request queuing, logging, and revocable, these three points are typical applications of the command pattern, which is mentioned later in this article, which can be compared in Word with similar text editing software, the user interface design of these software is widely used for reference to the characteristics of the command pattern. After encapsulating the request into a command object, a series of commands can be queued, recorded, revoked, and so on.

role

The following roles are included in the pattern:

command--command interface, in the example above, corresponds to the red-headed template of the Secretariat. The methods required to implement the detailed commands are defined. such as execute, Undo, and so on.

concreatecommand--Detailed command, above example, corresponding to the mouse capture file, crowing file.

These commands generally include the recipient's reference, for example, the mouse red-headed will be corresponding to a cat's reference instance, the Execute method will call the cat's method of mouse capture, crowing the same.

client--creates detailed commands and sets the recipient, which is the actual creator of the command. Corresponding to the Lion King. Each verbose command object is created at the time of creation. The recipient is already defined, and you need to be concerned about who will run it when you create the detailed command. Note that the client here is not usually said to use the user, and the client functions like the loader loader, creating different command objects and binding them dynamically in invoker.

invoker--requires the command to run the object, corresponding to the previous example of the Secretariat, their task is to ensure that the pass release. Each detailed command is guaranteed to be run.

receiver--recipients. The detailed run of the command, corresponding to the above example of a chicken cat, these actors will generally be combined in the detailed command. They have their own methods, and these methods are generally called in the Execute method of the verbose command.

Code Implementation

The implementation of UML diagrams such as the following see

For example, command is an interface for commands. Secretary Class Secretary combines this interface object, the Mousetrap and the crowing implement the Command interface. Because the logic is relatively simple, the direct code, the first is a simple to embarrassed command interface.

<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" ><span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" ><span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >public interface Command {public abstract void execute ();} </span></span></span>

Detailed commands include two, Catchmousecommand and Crowcommand

<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" ><span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" ><span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >public class Catchmousecommand implements Command{cat Cat;public Catchmousecommand (cat cat) {//TODO auto-generated C Onstructor stubthis.cat = cat;} @Overridepublic void Execute () {//TODO auto-generated method Stubcat. Catchmouse ();}} </span></span></span>

and

<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" ><span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" ><span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >public class Crowcommand implements Command{cock cock;public crowcommand (cock cock) {//TODO auto-generated construct or stubthis.cock = cock;} @Overridepublic void Execute () {//TODO auto-generated method Stubcock. Crow ();}} </span></span></span>

You can see that both of these verbose command classes combine the recipient class. Cat or cock, for simplicity, these two accept that this class only contains a corresponding method, such as the following

Cat

<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" ><span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" ><span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >//Cat Class-receiverpublic class Cat {//catch mouse method public void Catchmouse () {System.out.println ("Cat is Catching Mouse");} </span></span></span>

Cock

<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" ><span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" ><span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >//Rooster classes-receiverpublic class Cock {//crowing method public void Crow () {System.out.println (' cock is crowing ');}} </span></span></span>

The Secretary class combines the Command object and the two methods, setcommand because the verbose command is set, and Publiccommand is similar to a callback in a structured language, which invokes the Execute function of the verbose command when the command needs to be run, and the Secretary class acts as the initiator of the request. Does not care who runs the detailed command, how to run it, which realizes the decoupling of the requester and the implementation.

Invoker does not care about receiver, and vice versa.

<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" ><span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" ><span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >public Class Secretary {command command;public void setcommand (Command command) {this.command = command;} public void Publiccommand () {This.command.execute ();}} </span></span></span>

Lion in this case is the creator of the order. He created detailed commands and handed them over to the Secretary at the right time to publish and run (receiver completed), in software development practice this class is more like a loader, he establishes a mapping relationship, a specific invoker binding specific Concretecommand, The following article will be analyzed with the word editor software development.

<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" ><span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" ><span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >/** * Lion does not actually use the client, it acts like a loader loader, and its role is to bind different command objects (Catchmousecommand) for the trigger Invoker (the Secretary Object Secretary).

* This is like in the menu of similar word software, different menu item MenuItem is different Invoker, each menu item * will bind a command object, even multiple menu items may bind the same command object. * The menu item triggers its bound command object method when the user taps it.

*/public class Lion {Secretary Secretary;public Lion (Secretary Secretary) {//TODO auto-generated constructor stubthis.se Cretary = secretary;} public void Createcatchmouseorder () {Cat cat = new Cat (); Catchmousecommand Catchmousecommand = new Catchmousecommand (cat); Secretary.setcommand (Catchmousecommand);} public void Createcrowcommand () {Cock cock = new cock (); Crowcommand Crowcommand = new Crowcommand (cock); Secretary.setcommand (Crowcommand);}} </span></span></span>

After the above basic classes have been completed. We need to join the user program for testing, such as the following

<span Style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" ><span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" ><span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >public class UserApplication {/** This is the usual user program, that is, the context in which the command pattern is used. * @param args */public static void main (string[] args) {//TODO auto-generated method Stubsecretary secretary = new Secret ARY (); The role of//lion is similar to loader. Binds a Command object to Secretary (Invoker). Lion lion = New Lion (Secretary); Lion.createcatchmouseorder (); Secretary.publiccommand (); Lion.createcrowcommand (); Secretary.publiccommand ();}} </span></span></span> 

As can be seen from the test example, lion is dynamically binding a different command for secretary, which completes the request. In this example, when Secretary receives a detailed command, it Publiccommand (advertised), and in many cases, the announcement is driven by a user event, for example, when a MenuItem is initialized with a corresponding function. Only when the user clicks on the MenuItem, the callback method of the menu item is called Publiccommand, and then the actual operation is completed.
The results of this test example are as follows:

Cat is catching mouse
Cock is crowing

Extending the scene

The preceding code demonstrates a sample of the command pattern, which only answers the first half of the official definition. That is, the application of command pattern in software practice is the development of a text editor or IDE user interface, as an example to explain the request queuing, logging and revocable operation in the official definition.

"Request Queuing"

Let's say you frequently operate eclipse on a generic machine, and usually you'll see the following interface

 

The task behind a big push waiting is the request that is being queued, the reason for this phenomenon is the following diagram:

 

We ask the IDE to run requests that are encapsulated as command objects placed in the work queue, and each spare thread gets and runs the command object, but with limited resources. The scheduler needs to limit the number of threads that can be used. When there is a new thread spare. Queued Command objects are run sequentially, which is how the command pattern is applied in request queuing.

"Logging Request Log"

This is mainly used in management operations for large databases. The example presented in this paper is of little practical significance. In the maintenance of large database, all the operation modification is done by the command object, and some changes must be done in the way of the transaction. Because these changes are closely related to each other, for many long-time changes, the database can not be modified every change to do a backup, that requires too much resources, so that each time the modification of the Command object in a serialized way to save (store) on disk, every two checkpoint points between the modification , all saved up.

This way, when the system crashes, the command objects are loaded (load) from the disk by deserialization, and the undo operation of these commands is completed. This completes the database system recovery.

Completion of the above tasks requires not only the command object to support serialization operations. And there are new requirements for the command interface. For example, the following

 

 

Undo Undo Ctrl + Z

Or a sample of the previous article. The undo operation requires the object to return to the state it was in before the command was run, which required an undo method in the command interface.

<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" ><span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >public interface Command {public abstract void execute ();p ublic abstract void undo ();//New Undo Interface}</span></ Span>

Rooster class Cock An instance of the crowing frequency is required inside. If the rooster crowing frequency has high, medium and low three kinds. Normally the crowing frequency is low and may be crowing 2 times a week. But after the order was issued, the frequency of crowing increased significantly. Reached 7 times a week and that's the new cock class

<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" ><span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >//Rooster class-receiverpublic class Cock {public static final int low = 0;public static final int MEDIUM = 1;public static fina l int high = 2;private int crowfrequence; Add a record crowing frequency state instance, default feel low//crowing method public void Crow () {System.out.println ("cock is crowing"); Setcrowfrequence (high); After calling the Crowing method, the frequency is high}//getter and the setter function, gets and sets the current crowing frequency public int getcrowfrequence () {return crowfrequence;} public void setcrowfrequence (int crowfrequence) {crowfrequence = crowfrequence;} @Overridepublic String toString () {//TODO auto-generated method Stubreturn "Crowfrequence is" + Crowfrequence;}} </span></span>

In the verbose command. A state is required to record the crowing frequency before the command is run, and the recorded frequency value is restored when the undo operation is run after the Thunder.

<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >public class Crowcommand implements Command{cock Cock;int Prevstage;    Record the crowing frequency state before the command runs public crowcommand (cock cock) {//TODO auto-generated constructor stubthis.cock = cock;} @Overridepublic void Execute () {//TODO auto-generated Method stubprevstage = Cock.getcrowfrequence ();//record before running the command.

System.out.println ("Before execute:" + cock); cock. Crow (); System.out.println ("After execute:" + cock);} @Overridepublic void Undo () {//TODO auto-generated method Stubcock.setcrowfrequence (prevstage);//Run undo operation, Set prevStageSystem.out.println for Hold ("after undo:" + cock);}} </span>


Rewrite the test example to join the run undo operation, the resulting results such as the following

This is a simpler undo situation, but it saves an instance domain. And can only undo the previous step, very often need to establish the history of the operation, so that you need to save a running command of the linked list, each linked list contains the ability to undo the command and its detailed implementation, this is similar to Word and PS, such as the application of a very wide range of software, do not repeat.

"Macro Command"

This is a special class of commands. Define a series of commands in this class list, run and undo. Run all the commands in the list again. Ability to define and delete the detailed commands in the list, skilled use of Word's students have used macro commands, such as the graduation thesis template for the font, paragraph, header and footer all the formatting requirements can be simply defined as a macro template, Simply applying this macro template will enable you to set the current document to the required format of your paper at high speed.

structure

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqva2xwy2hhbg==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center ">

This structure is similar to the UML diagram above and can be controlled by itself.

Official definition

effects and points of attention

1) The command pattern decouples the requesting caller from the actual run, conforming to the dependency inversion principle.

2) The detailed command object can be extended like any other object.

This is a special object that abstracts functions into classes, which are described earlier than the advantages of common functions.

3) The structure conforms to the development closure principle, and adding new classes does not require modifying the original code structure.

4) How intelligent is the detailed command object? Whether the command object must depend on receiver completion, depends on the degree of change.

The detailed object of this article is a method that relies entirely on the recipient.

5) The command is necessary to undo the operation. The undo operation needs to maintain the status value. Assuming that the state is a more complex object, you need to introduce many other instances to represent it. Whether the revocation process will cause other changes within the recipient.

relationships with other models

The menu tree for large text editing software is complex, and in addition to the macro commands mentioned earlier, the combination mode allows you to implement a menu tree command with a multi-layered branching structure.

The memo mode is used when recording the complex state of the recipient. Use this mode to complete the state recovery after the undo operation.

Finishing

Command mode is a widely used mode in software practice, the application of this mode is more special, especially for the menu tree and database-related function module, the advantages of such a pattern is obvious, it separates the task requester and the runner, encapsulates the behavior into objects, thus can complete similar request to participate in the number of, State save/restore, Undo, redo, macro commands and more. The most typical applications of this mode are the application of the Software User menu tree development, event-driven, database log maintenance and recovery, etc. as command objects. Even when you add a Actionbar.tablistener listener object to your program, the framework layer also uses command mode.

Welcome to share Communication, progress together ~

----------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------Note: Welcome to share, reprint please declare ~ ~----------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------

Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

For example, in command pattern

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.