• 命令模式(Command Pattern)


    命令模式:

      解决「请求者」与「执行者」之间的耦合。

      比如:

        一个面馆子里来个一位客人,客人在菜单上写了「鱼香肉丝盖饭」并交给了服务员,服务员把菜单拿到后堂,交给了大厨!!!

              

      其中,订单就起解耦的作用!!!

    原理:

      

      Command 是命名模式的抽象接口,所有的具体命名都需要实现这个接口

      Client 相当于上面例子中的客人

      Receiver 相当于上面例子中的厨师,它最后进行具体的实施

      Invoker 相当于例子中的服务员,在Invoker中,实例化具体的Command对象

      ConcreteCommand 相当于订单,实现了Command接口

    例子:

      比如:

        实现一个遥控器,可以控制电灯的开或者关!

    package Command;
    
    public interface Command {
        public void execute();
    }
    Command
    package Command;
    
    public class Light {
        public void on() {
            System.out.println("light up");
        }
    
        public void off() {
            System.out.println("douse the glim");
        }
    }
    Light
    package Command;
    
    public class LightOnCommand implements Command{
        Light light;
    
        public LightOnCommand(Light light) {
            this.light = light;
        }
    
        public void execute() {
            light.on();
        }
    }
    LightOnCommand
    package Command;
    
    public class SimpleRemoteControl {
        Command slot;
    
        public SimpleRemoteControl() {}
    
        public void setCommand(Command command) {
            this.slot = command;
        }
    
        public void buttonWasPressed() {
            slot.execute();
        }
    }
    SimpleRemoteControl
    public class Main {
    
        public static void main(String[] args) {
    
            SimpleRemoteControl remote = new SimpleRemoteControl();
            Light light = new Light();
            LightOnCommand lightOn = new LightOnCommand(light);
    
            remote.setCommand(lightOn);
            remote.buttonWasPressed();
    
        }
    }
    main

    应用场景:

      线程池、队列请求、记录宏 。。。

  • 相关阅读:
    Stream流的使用
    ThreadLocal原理和使用场景?
    Python+Appium实现APP自动化测试
    查看Linux系统版本信息
    linux命令之修改yum源为国内镜像
    lsb_release: command not found 解决
    docker安装mysql
    win10 系统出现“你不能访问此共享文件夹,因为你组织的安全策略阻止未经身份验证的来宾访问。”
    python常用sys模块
    python常用os模块
  • 原文地址:https://www.cnblogs.com/Mr-Wenyan/p/10212098.html
Copyright © 2020-2023  润新知