Command pattern)

Source: Internet
Author: User
Tags object serialization

1. What is the command mode?

The command mode encapsulates the details of the method call to decouple the requester and executor. The specific process is as follows:

1. From the perspective of the requester (customer)

The requester (customer) sends a request-> the caller (system) constructs a command object encapsulation request-> the caller calls the specified method of the command object (the request is executed)

Obviously, the requester does not know who the executor is, nor the specific execution details. Of course, the requester does not care about this either. It only needs to know that the request has been executed.

2. From the perspective of Executors (lower-layer components)

Executors (lower-layer components) are called-> executors call internal methods (requests are executed)

Similarly, the executor does not know who the requester is, or even the caller. But it does not matter. The executor only needs to do his job well in the current score, and there is no need to know the leadership information.

3. From the caller (system) perspective

Request received-> Create a command object encapsulation request-> call the action of the command object to execute the request when appropriate (the request is executed)

The caller does not know who the executor is or the requester. The caller is only responsible for constructing commands and controlling command execution. This is enough.

We can see the low coupling relationship between objects from the above:

The requester (customer) and executor (lower-layer component) are completely decoupled, And the caller as the intermediary does not understand the details of the requester and executor. They are well protected.

This is exactly what we want.

Ii. Example

In the real world, any slightly complicated subsystem should have a set of commands, such as the operating mechanism of restaurants:

Customer A came to the restaurant to order a bowl of noodles (send a request)-> the clerk recorded it (create a command) -> the waiter threw the receipt to the kitchen.-> the cook C quickly prepared a bowl of noodles (the request was executed)

The customer does not know who will cook the bowl, nor does the clerk at the counter know. The cook does not know who has ordered the bowl, but only knows that the bowl can be rested after it is finished.

Is it similar to the command mode?

Use code to implement the above Mechanism

First, we need a command interface. After all, commands are the core of the command mode, and everything is a fantasy without commands.

Package commandpattern;/*** @ author ayqy * defines the command interface */public interface command {public abstract void execute (); // you only need to define a unified execution method}

If commands are executed, the executors must be executors. Otherwise, only the generals do not have small soldiers. The executors of restaurants are chefs:

Package commandpattern; /*** @ author ayqy * defines the chef base class */public abstract class Chef {// defines the cook's public attributes here/*** defines the cooking method */public abstract void cook (); // define other useful methods here}

We also need to implement specific chefs with specialized skills:

COOK:

Package commandpattern;/*** @ author ayqy * defines the professional cook */public class noodleschef extends chef {@ overridepublic void Cook () {system. out. println ("a bowl of delicious ramen ");}}

Chefs who make cakes:

Package commandpattern;/*** @ author ayqy * defines the professional cook */public class piechef extends chef {@ overridepublic void Cook () {system. out. println ("a delicious big pie ");}}

With a soldier and a general, we still need a complete set of commands:

Package commandpattern;/*** @ author ayqy * implement the specific noodlescommand */public class noodlescommand implements command {private noodleschef chef; // professional cook public noodlescommand () {chef = new noodleschef () ;}@ overridepublic void execute () {chef. cook (); // call other required methods }}
Package commandpattern;/*** @ author ayqy * implement the specific piecommand */public class piecommand implements command {private piechef chef; // The cook who specializes in making cakes public piecommand () {chef = new piechef () ;}@ overridepublic void execute () {chef. cook (); // call other required methods }}

The preparation is complete. The restaurant can be opened.

Iii. Example

A test class is required:

Package commandpattern;/*** @ author ayqy * implement the test class */public class test {public static void main (string [] ARGs) {system. out. println ("Command pattern restaurant opened .. "); System. out. println ("first customer Mr. X"); system. out. println ("Mr. X: Hello, I need a bowl of noodles. I'm so hungry"); noodlescommand ncmd = new noodlescommand (); system. out. println ("clerk at the counter: OK, I have already noted it down, right away"); system. out. println ("counter attendant: Kitchen ~~, The ticket was received "too many n0000.exe cute (); system. Out. println (" Mr. X: so fast! "); System. out. println (); system. out. println ("Mr. XX, the second customer"); system. out. println ("Mr. XX: Hello, I need a piece of cake, take it for 20 minutes later"); piecommand pcmd = new piecommand (); system. out. println ("clerk at the counter: OK, I have already noted down"); system. out. println ("15 minutes later"); system. out. println ("counter attendant: Kitchen ~~, The order is received "too many pcmd.exe cute (); system. Out. println (" Mr. XX: It's time! ");}}

Result example:

We can see from the example:

1. The caller (Clerk at the counter) can control the specific execution time, but the details of the specific Executor (Cook) are completely unclear.

2. the requester (customer) has no idea about the restaurant's operating mechanism. He does not know whether the order is made by a cook, a waiter, or bought from the next door ..

3. The executor (Cook) does not know the requester's situation at all. It only does its job and does not know anything else.

Iv. Command mode Extension

1. Macro commands (sequential execution of multiple commands)

We can define "Command commands" for implementation (the execute method of this special command calls the execute method of several other commands in sequence ..)

2. Undo

If a lot of customers have ordered a lot of meals, after a while several customers can't wait to cancel the order. How can we achieve this?

Maintain a command list and record the created commands. You need to find the corresponding commands during undo and execute the Undo operation.

Of course, the premise is that the command object supports revocation, and we need to make some modifications:

Package commandpattern;/*** @ author ayqy * defines the command interface */public interface command {public abstract void execute (); // you only need to define a unified execution method public abstract void undo (); // define a unified revocation method}

Commands may have different revocation operations. Therefore, they are defined as abstract methods and are implemented by sub-classes.

* How does one support multi-step sequential revocation?

The restaurant example may not require such a feature. Think about another scenario, text editor.

The user has issued a series of commands to complete some column operations, and later found that this is not required, the user will undo the modification (CTRL + Z ), in this case, we need to perform the opposite operation to restore the content. How can we achieve this?

We still need to first implement the Undo behavior of each command (execute operations in the reverse order of execute). In addition, we also need a stack to record the operations that have been executed, to enable revocation to the initial state.

3. Queue requests

We can create a working thread to take charge of all operations. Imagine there is a channel where the input is a different command and the output is the execution result of the command.

Maybe the worker thread is making a big pie for the last moment and has gone out to buy food for the next moment ..

* What are the benefits of doing so?

The operation can be restricted to several specified threads and controlled.

4. Log request

It is mostly used for the implementation of database management systems. We need to record a series of operations (such as writing them on a hard disk) and read them out when a system fault occurs to restore data. How can this problem be achieved?

Use object serialization to save objects (record logs) and deserialize objects (Restore transactions) as needed)

V. Summary

The command mode can effectively decouple the requester and executor, and provides some additional benefits (such as support for Undo operations, queue requests, logging, and so on)

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.