zoukankan      html  css  js  c++  java
  • 命令模式

    手腕旧伤又疼了,想当键盘侠都难,最近都没有输入输出,颓废了


    1. 命令模式(Command Pattern)

    请求 封闭成对象,以便使用命令来参数化其它对象,或者将命令对象放入队列中进行排队对行为进行记录、撤销或重做、事务等处理。应用在请求行为和实现者需要解耦的场合,以便撤销等动作


    命令模式的组成:

    • Command:封装命令的对象
    • Receiver:命令真正的执行者
    • Invoker:通过它来调用命令
    • Client:可以设置命令与命令的接收者




    2. 流程

    实现一个基于命令模式的开关灯功能


    2.1 Receiver(灯 Light)

    public class Light {
    
        public void on() {
            System.out.println("Light is on");
        }
    
        public void off() {
            System.out.println("Light is off");
        }
    }
    


    2.2 Command 命令

    // 命令接口
    public interface Command {
        void execute();
    }
    

    // 命令接口
    public class LightOnCommand implements Command {
        Light light;
    
        public LightOnCommand(Light light) {
            this.light = light;
        }
    
        @Override
        public void execute() {
            light.on();
        }
    }
    

    // 命令接口
    public class LightOffCommand implements Command {
        Light light;
    
        public LightOffCommand(Light light) {
            this.light = light;
        }
    
        @Override
        public void execute() {
            light.off();
        }
    }
    


    2.3 Invoker

    public class Invoker {
        private List<Command> commands = new LinkedList<>();
    
        public void receiveCommand(Command command) {
            commands.add(command);
        }
    
        public void executeCommand() {
            for (Command temp : commands) {
                temp.execute();
            }
            // 这里可以记录命令的执行顺序
            commands.clear();
        }
    }
    


    2.4 Client

    public class Client {
        public static void main(String[] args) {
            Light light = new Light();
            LightOnCommand lightOnCommand = new LightOnCommand(light);
            LightOffCommand lightOffCommand = new LightOffCommand(light);
            Invoker invoker = new Invoker();
            invoker.receiveCommand(lightOnCommand);
            invoker.receiveCommand(lightOffCommand);
            invoker.executeCommand();
        }
    }
    

  • 相关阅读:
    [转] 使用C#开发ActiveX控件
    [转] error LNK2026: 模块对于 SAFESEH 映像是不安全的
    Struts2详细说明
    a web-based music player(GO + html5)
    oracle_单向函数_数字化功能
    UVA 1364
    ORA-12545: Connect failed because target host or object does not exist
    左右v$datafile和v$tempfile中间file#
    二十9天 月出冲击黑鸟 —Spring的AOP_AspectJ @annotation
    Shell编程入门(再版)(在)
  • 原文地址:https://www.cnblogs.com/Howlet/p/15264784.html
Copyright © 2011-2022 走看看