zoukankan      html  css  js  c++  java
  • 命令模式(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

    应用场景:

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

  • 相关阅读:
    cf Inverse the Problem (最小生成树+DFS)
    cf Make It Nondeterministic (简单贪心)
    cf Learn from Life (简单贪心)
    hdu 5057 Argestes and Sequence (数状数组+离线处理)
    hdu 5056 Boring count (类似单调队列的做法。。)
    hdu 5055 Bob and math problem (很简单贪心)
    三样东西能让女人幸福一生
    第01课 OpenGL窗口(4)
    爱情要不要吃回头草?(林忆)
    第01课 OpenGL窗口(3)
  • 原文地址:https://www.cnblogs.com/Mr-Wenyan/p/10212098.html
Copyright © 2011-2022 走看看