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

命令模式(Command),将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。[DP]

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

// 具体命令类,实现了命令接口
class ConcreteCommand implements Command {
    private Receiver receiver;

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

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

// 接收者类,知道如何执行请求
class Receiver {
    public void action() {
        System.out.println("Receiver: 执行操作");
    }
}

// 调用者类,负责发送命令
class Invoker {
    private Command command;

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

    public void setCommand(Command command) {
        this.command = command;
    }

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

// 客户端代码
public class Client {
    public static void main(String[] args) {
        // 创建接收者
        Receiver receiver = new Receiver();
        // 创建具体命令对象,并将接收者传递给它
        Command command = new ConcreteCommand(receiver);
        // 创建调用者,并将命令传递给它
        Invoker invoker = new Invoker(command);
        // 通过调用者执行命令
        invoker.executeCommand();
    }
}

 

相关推荐

  1. 行为设计模式命令模式

    2024-03-10 12:44:04       33 阅读
  2. 设计模式行为设计模式——命令模式

    2024-03-10 12:44:04       19 阅读
  3. 行为设计模式

    2024-03-10 12:44:04       12 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-10 12:44:04       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-10 12:44:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-10 12:44:04       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-10 12:44:04       20 阅读

热门阅读

  1. 数据仓库的主流分层架构

    2024-03-10 12:44:04       26 阅读
  2. 基于qt实现的类的序列化和反序列化

    2024-03-10 12:44:04       23 阅读
  3. 云原生技术实践:Kubernetes集群的部署与运维

    2024-03-10 12:44:04       19 阅读
  4. pytorch CV入门4-使用MobileNet解决视觉相关问题

    2024-03-10 12:44:04       19 阅读
  5. 【pytorch可视化工具】

    2024-03-10 12:44:04       24 阅读
  6. 基于Python调用SCIP求解器的入门文档

    2024-03-10 12:44:04       28 阅读
  7. Springboot 分片上传客户端Demo

    2024-03-10 12:44:04       26 阅读
  8. AI 改变生活

    2024-03-10 12:44:04       19 阅读
  9. jenkins 迁移(centos7服务器之间)

    2024-03-10 12:44:04       23 阅读
  10. Python2.x 与 3.x 版本区别

    2024-03-10 12:44:04       22 阅读