Design Mode (10) --- command mode, design mode ---

Source: Internet
Author: User

Design Mode (10) --- command mode, design mode ---

I. Introduction:

There is a barbecue stall on the side of the road, and a boss is responsible for barbecue food for the guests. If there are few guests, the boss can accurately remember everyone's requirements. As the number of guests increases, the number of requirements increases, making it difficult for the boss to meet everyone's requirements. What should the boss do?

First of all, I would like to explain why there are too many guests and the boss cannot meet everyone's requirements, because "in the words of programmers, it is due to tight coupling ". Loose coupling can solve this problem, that is, the command mode described in this article. The tightly coupled code is provided first:

Class Program {static void Main (string [] args) {extends er extends ER = new extends Er (); extends er. bakeChickenWing (); Console. read () ;}} public class extends er // boss {public void BakeMutton () {Console. writeLine ("bake mutton");} public void BakeChickenWing () {Console. writeLine ("bake chickenwing ");}}View Code

 

Ii. Definition:

Command mode: encapsulate a request as an object so that you can parameterize the customer with different requests, queue requests or record request logs, and support unrecoverable operations.

Explanation: The Request command is encapsulated as an object and recorded in logs. It supports command revocation.

 

Iii. UML diagram and basic code:

Basic code:

Class Receicer {public void Action () {Console. writeLine ("execution request") ;}} abstract class Command {protected Receicer extends er; public Command (Receicer extends ER) {this. extends ER = extends er;} abstract public void Execute ();} class ConcreteCommand: Command {public ConcreteCommand (Receicer extends ER): base (extends ER) {} public override void Execute () {extends er. action () ;}} class Invoker {private Command command; public void SetCommand (Command command) {this. command = command;} public void ExecuteCommand () {command. execute ();}}

Call:

Receicer receiver = new Receicer();            Command command = new ConcreteCommand(receiver);            Invoker invoker = new Invoker();
invoker.SetCommand(command);

invoker.ExecuteCommand();

Explanation: maps guests to the hotel for meals. The Receiver is the Receiver of the Command, which is equivalent to the chef in the hotel; the Command abstract class. The ConcreteCommand is a specific Command, which is equivalent to a la carte request. The Command should contain the Receiver of the Command. Invoke is a courier of commands. It is equivalent to a hotel attendant who records the order request and sends it to the kitchen.

 

4. Examples:

The school's Senior One students undergo military training. The principal issued a 10000-meter command for the students. Throughout the process: the principal issues a command to the military training instructors, the instructors send the command to the students, and the students receive the command and execute the corresponding operations. In the following example, the runner is a student and runs a 10000-meter command. Command is a Command, and the receiver of the Command must be known. The Drillmaster is an instructor and the instructor must know what the command is and send the command.

// The principal issues a 1000-meter command for the student. The instructor sends the command to the student. The student is the receiver of the command. // The client is the principal, the sender of the command must know the specific command, Receiver, and sender class Program {static void Main (string [] args) {receiver er extends ER = new Receiver Er (); command command = new ConcreteCommand (reset ER); Drillmaster drillmaster = new Drillmaster (command); drillmaster. executeCommand (); Console. read () ;}// command Receiver public class extends er {public void Run1000Meters () {Console. writeLine ("Running 10000 meters") ;}// abstract Command public abstract class Command {protected extends er; public Command (extends er extends ER) {this. extends ER = extends er;} public abstract void Action () ;}// for specific commands, you must know the receiver public class ConcreteCommand: Command {public ConcreteCommand (extends er extends ER): base (extends ER) {} public override void Action () {extends er. run1000Meters () ;}}// INSTRUCTOR: the passer of the Command, responsible for calling the method of the command object to ensure that the Command is executed by the public class Drillmaster {public command Command command; public Drillmaster (Command command Command) {this. command = command;} public void ExecuteCommand () {command. action ();}}View Code

 

V. Solve the Problems in the Introduction

The recipient of the order, the boss (chef ):

public class Receiver    {        public void BakeMutton()        {            Console.WriteLine("bake mutton");        }        public void BakeChickenWing()        {            Console.WriteLine("bake chickenwing");        }    }

 

Ordering command:

public abstract class Command    {        protected Receiver receiver;        public Command(Receiver receiver)        {            this.receiver = receiver;        }        abstract public void Execute();    }    class ConcreteCommand1 : Command    {        public ConcreteCommand1(Receiver receiver)            : base(receiver)        { }        public override void Execute()        {            receiver.BakeMutton();        }    }    class ConcreteCommand2 : Command    {        public ConcreteCommand2(Receiver receiver)            : base(receiver)        { }        public override void Execute()        {            receiver.BakeChickenWing();        }    }

 

Add a waiter to record the order of the guests and send them to the chefs. The ordering command can be added or canceled.

Public class Invoker {private IList <Command> commands = new List <Command> (); public void AddCommand (Command command) {commands. add (command); Console. writeLine ("add order" + command. toString ();} public void CancelCommand (Command command) {commands. remove (command); Console. writeLine ("cancel order" + command. toString ();} public void ExecuteCommand () {foreach (Command command in commands) {command. execute ();}}}

 

Client call:

Receiver receiver = new Receiver();            Command command1 = new ConcreteCommand1(receiver);            Command command2 = new ConcreteCommand2(receiver);            Invoker invoker = new Invoker();            invoker.AddCommand(command1);            invoker.AddCommand(command2);            invoker.CancelCommand(command1);            invoker.ExecuteCommand();

 

Vi. Advantages and Disadvantages and applicable scenarios

Advantages:

It is easier to design a command queue. When necessary, it is easier to include the command into the log. The party that allows receiving the request decides whether to reject the request; it is easier to undo and redo commands. Because adding a new command class does not affect other classes, it is easier to add a new command class.

Disadvantages:

The system may have too many specific command classes.

 

Applicable scenarios:

Personal Understanding: The command mode can be used to show its advantages.


JAVA is the design pattern.

The design pattern is a summary of a method for designing a program, such as The Singleton pattern.

Public class {
Private static final A a = new ();
Private (){}
Public static A getInstance (){
Return;

}

}

In this way, A can always have only one instance, because its constructor is already private, you must use the getInstance method to obtain the instance. No matter how many threads or A single thread gets, only one A object is serving you.

Java design mode (command mode)

Let's talk about the command mode first. For example, the command was created by the Emperor Yudi, the Monkey King of the United States, which is the sacred purpose. Then it was pointed out that the recipient of the Holy Spirit, Monkey King of the United States, was the only one who conveyed the command. This process is an application of the command mode.
The advantage is that the Jade Emperor will not directly deal with the Monkey King. He only needs to encapsulate the commands in the holy decree and send them to the white Venus to communicate other things.
Next, let's explain the observer model. In the travel to the West as an example, the Tang sanzang was trapped by a red child. Sun Wukong asked him to pray for the Bodhisattva, while the Bodhisattva listened and sent his pearl bottle to the sea, I saw a turtle carrying a bottle up .... The tortoise is the observer, and the object to be observed is the bodhisattva. Here we can see the difference between the command mode. The tortoise is waiting to observe the action of the Bodhisattva, And the Jade Emperor sends his own command. Sometimes it is messy. The observer is looking at how the turtles are implemented, and the command is about how the people who issue the command arrange it ....
Sorry!

Related Article

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.