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

命令模式(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();
    }
}
相关推荐
电子IT笔记2 小时前
人走了,记录不能“空白”: MES×HR 离职人员下拉回显实战
设计模式
博风20 小时前
8、设计模式应用举例:适配器模式:Iterator接口与Enumeration接口
设计模式·适配器模式
高晶21 小时前
ARM 嵌入式 Linux 系统 U-Boot 开发与移植实战M
设计模式·程序员
geovindu1 天前
rust: Chain of Responsibility Pattern
开发语言·后端·设计模式·rust·责任链模式·行为模式
拆房老料1 天前
【第四部分:Agentic 智能体设计模式】15.为什么 Agent 也需要设计模式
人工智能·设计模式·ai·ai-native
geovindu1 天前
rust: Chain of Responsibility Pattern (续)
开发语言·后端·设计模式·rust·责任链模式·行为模式
Lost of 程序猿1 天前
责任链模式实战:审批流里“层层把关“的艺术
后端·设计模式·asp.net·责任链模式
希洛兔2 天前
状态模式详解:让对象随内部状态自动改变行为
java·设计模式·状态模式
博风2 天前
7、设计模式应用举例:策略模式:加密、解密文件
设计模式·策略模式
4SAPI2 天前
Provider Adapter设计模式:如何让AI应用支持多个模型
网络·人工智能·设计模式