Design Mode: Command Pattern)

Source: Internet
Author: User

Design Mode: Command Pattern)

 
What is the command mode?

Official explanation: encapsulate a request under an object as a command and pass it to invoker object. invoker object looks for the appropriate objectwhich can handle this command and pass the command to the corresponding object and that object executes the command.
Encapsulate a request object as a command and pass it to the caller (command sender) object. During the call period, the object looks for an appropriate object that can process this command and passes this command to the response (command recipient) object. Then the object executes this command.

Common Explanation: encapsulate a command into a (request) object, define a command caller (sender), a command Executor (receiver), and associate the command with the command receiver, in addition, the command sender can hold this command (a command caller can hold multiple commands). When the client needs to issue a command, the command sender can call the relevant command.

Why use command mode?

The command abstraction is encapsulated to make the command Easy to modify, extensible, and highly reusable. The code of the old command is not required during expansion. You can combine two simple commands into a new one.

Separate a command from a specific operation (by the receiver) of the command, so that the command does not need to care about the specific operation of the command. You only need to determine the recipient of the command.

The command is associated with the command sender (command invocation period), so that the client does not need to care about any details of the command. You only need to use the command sender to start a command.

How to Use the command mode?
The command mode UML diagram is as follows:

Description of each component:

Command: the abstract body of a Command. It defines an interface for executing commands.

Invoker: The caller of a command. It contains one or more command objects and is called by a client.

ConcreteCommand (specific command): a specific command is associated with a command receiver, and the method for executing commands (determined by the associated command recipient) is implemented.

Extends Er (command recipient): defines specific response operations for a series of command actions and is associated with some commands.

Client: the Client that initiates the command. Before that, you must determine the associations and cohesion. Note: The code for determining the relationship between components can also be encapsulated as a third-party class and called by the client.

Command mode scope:
1. In a scenario where the request-> response function is available and there are many types of requests, the response function is expected to be transparent to the client.
2. In a scenario, some operations must be performed based on the request operation parameter object.
3. When you want to create and execute a request object at a different time. That is, you do not need to use the command immediately after it is created.
4. When you need to support rollback, recovery, recording, and other functions in a scenario.

Application instance:
Now we have such a scenario. Do you still remember the example of the Builder mode? after constructing the Role of the cold ice shooter, we need to issue a command to release the hero's skills, we can do this:
1. First, we abstract a Command interface and define an interface for executing commands. Then Abstract The Role interface and define the release method interface of QWER's four skills. Use HanBingRole to implement this interface and skill release method.

Interface Command {public void excute ();} public interface Role {void QSkill (); void WSkill (); void ESkill (); void RSkill ();} public class HanBingRole implements Role {@ Override public void QSkill () {System. out. println (ice cream shooting !!!); } @ Override public void WSkill () {System. out. println (!!!); } @ Override public void ESkill () {System. out. println (empty length !!!); } @ Override public void RSkill () {System. out. println (magic crystal arrow );}}

2. After the abstraction is complete, we need to define a specific command class and depend on the command receiver (Role) so that the receiver can execute the specific commands (role. XSkill ()).

public class QSkillCommand implements Command {    private Role role;    public QSkillCommand(Role role) {        this.role = role;    }    @Override    public void excute() {        role.QSkill();    }}public class WSkillCommand implements Command {    private Role role;    public WSkillCommand(Role role) {        this.role = role;    }    @Override    public void excute() {        role.WSkill();    }}public class ESkillCommand implements Command {    private Role role;    public QSkillCommand(Role role) {        this.role = role;    }    @Override    public void excute() {        role.ESkill();    }}public class RSkillCommand implements Command {    private Role role;    public QSkillCommand(Role role) {        this.role = role;    }    @Override    public void excute() {        role.RSkill();    }}

3. The specific commands and receivers are defined. Next we need a command sender (Invoker). Because there are many specific commands, a skill type enumeration SkillType (QWER) can be defined here ), define a map in Invoker so that the client determines the association between skill types and specific commands.

enum SkillType {    QSKILL,WSKILL,ESKILL,RSKILL}public class SKillInvoker {    private Map
  
    commandMap;    SKillInvoker(Map
   
     commandMap) {        this.commandMap = commandMap;    }    public void castQSkill(){        commandMap.get(SkillType.QSKILL).excute();    }    public void castWSkill(){        commandMap.get(SkillType.WSKILL).excute();    }    public void castESkill(){        commandMap.get(SkillType.ESKILL).excute();    }    public void castRSkill(){        commandMap.get(SkillType.RSKILL).excute();    }}public class client {    public static void main(String[] agrs) {        HanBingRole hanBingRole = new HanBingRole();        Map
    
      commandMap = new HashMap<>();        commandMap.put(SkillType.QSKILL, new QSkillCommand(hanBingRole));        commandMap.put(SkillType.WSKILL, new WSkillCommand(hanBingRole));        commandMap.put(SkillType.ESKILL, new ESkillCommand(hanBingRole));        commandMap.put(SkillType.RSKILL, new RSkillCommand(hanBingRole));        SKillInvoker sKillInvoker = new SKillInvoker(commandMap);        sKillInvoker.castQSkill();        sKillInvoker.castWSkill();        sKillInvoker.castESkill();        sKillInvoker.castRSkill();    }}
    
   
  

Here, other attributes and instantiation methods of HanBingRole are simplified for the sake of conciseness, and the Builder mode is not used. In actual development,HanBingRole may be instantiated using other creation ModesFor specific usage of the Creation Mode, read my previous articles. In addition, the ing between skill types and commands is also the most direct method. In actual development,It may be implemented through configuration or other methods that are easy to modify and expand..

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.