命令模式

2551 查看

描述:一个对象可以发一些命令让接受者帮助它执行,命令的发起者和接收者不必耦合,两者的沟通通过命令的传递进行沟通。

场景:某个boss经常会指点江山,让coder为他写代码,做报告,身为coder只能执行命令。

实现:

抽象命令

interface Command {
    void coding();
    void report();
}

定义一个coder,负责执行commad

class Coder {
    void exe(String cmd) {
        System.out.println("I am coder, get the cmd: " + cmd);
    }
}

具体的命令, 这个命令的执行是coder去执行的

class MyCommand implements Command {
    Coder coder;
    @Override
    public void coding() {
        coder.exe("coding");
    }
    @Override
    public void report() {
        coder.exe("report");
    }
}

定义一个boss,专门指点江山,命令的执行细节他不需要知道

class Boss {
    Command cmd;
    Boss(Command cmd) {
        this.cmd = cmd;
    }
    void coding() {
        cmd.coding();
    }
    void report() {
        cmd.report();
    }
}

客户端调用

public class CommandDemo {
    public static void main(String[] args) {
        Command cmd = new MyCommand();
        Boss boss = new Boss(cmd);
        boss.coding();
        boss.report();
    }

}