美文网首页
行为型模式 --- 命令模式

行为型模式 --- 命令模式

作者: 十二找十三 | 来源:发表于2020-09-05 10:39 被阅读0次
package study.org;

public class Demo {
    public static void main(String[] args) {
        Receiver receiver = new Receiver();
        Command command = new MyCommand(receiver);
        Invoker invoker = new Invoker(command);
        
        invoker.action();
    }
}

class Receiver {
    public void action() {
        System.out.println("command received!");
    }
}

interface Command {
    void execute();
}

class MyCommand implements Command {
    private Receiver receiver;

    public MyCommand(Receiver receiver) {
        this.receiver = receiver;
    }

    @Override
    public void execute() {
        receiver.action();
    }
}

class Invoker {

    private Command command;

    public Invoker(Command command) {
        this.command = command;
    }

    public void action() {
        command.execute();
    }
}

相关文章

网友评论

      本文标题:行为型模式 --- 命令模式

      本文链接:https://www.haomeiwen.com/subject/duixektx.html