命令模式(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

应用场景:

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

原文地址:https://www.cnblogs.com/Mr-Wenyan/p/10212098.html