大话设计模式-命令模式

UML

命令的接收执行者

/** * @ClassName: Receiver * @Author: Leo * @Description: 命令的接收执行者 * @Date: 2019/5/21 10:26 */
public class Receiver {
    public void action() {
        System.out.println("执行请求!");
    }
}

抽象命令类

/** * @ClassName: Command * @Author: Leo * @Description: 抽象命令类 * @Date: 2019/5/21 10:26 */
public abstract class Command {
    protected Receiver receiver;

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

    /** * 执行命令 */
    public abstract void execute();
}

具体的命令类

/** * @ClassName: ConcreteCommand * @Author: Leo * @Description: 具体的命令类 * @Date: 2019/5/21 10:27 */
public class ConcreteCommand extends Command {
    public ConcreteCommand(Receiver receiver) {
        super(receiver);
    }

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

接收命令并通知去执行命令

/** * @ClassName: Invoker * @Author: Leo * @Description: 接收命令并通知去执行命令 * @Date: 2019/5/21 10:30 */
public class Invoker {
    private Command command;

    /** * 设置命令 * * @param command */
    public void setCommand(Command command) {
        this.command = command;
    }

    /** * 通知执行命令 */
    public void executeCommand() {
        command.execute();
    }

}

测试类

/** * @ClassName: Main * @Author: Leo * @Description: 测试类 * @Date: 2019/5/21 10:23 */
public class Main {
    public static void main(String[] args) {
        Receiver receiver = new Receiver();
        Command command = new ConcreteCommand(receiver);

        Invoker invoker = new Invoker();
        invoker.setCommand(command);
        invoker.executeCommand();
    }
}

运行结果

执行请求!
全部评论

相关推荐

点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
11-27 10:46
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务