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

命令模式(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();
    }
}
相关推荐
小程故事多_802 小时前
Claude Code 全流程梳理,从需求输入到工具执行的完整逻辑
人工智能·设计模式·智能体·claude code·harness
cui17875686 小时前
排队免单模式:从爆火到优化,探寻实体商业新出路
大数据·人工智能·设计模式·个人开发·设计规范
医疗信息化王工6 小时前
26种不良事件表单的通用设计模式与实现
设计模式
mounter6256 小时前
【内核精进】Linux Kernel 设计模式(一):引用计数与可见性的艺术
linux·设计模式·linux kernel
workflower6 小时前
机器人应用-高空立面清洁
人工智能·深度学习·设计模式·机器人·软件工程·软件构建
likerhood6 小时前
设计模式:原型模式(Prototype Pattern)java版本
java·设计模式·原型模式
小程故事多_801 天前
从Claude Code源码中,拆解13个可直接复用的Agentic Harness设计模式(生产级实战解析)
人工智能·设计模式·智能体·claude code·harness
踩着两条虫1 天前
VTJ 平台六大设计模式落地实战指南
开发语言·前端·人工智能·低代码·设计模式·重构·架构
石油人单挑所有1 天前
基于多设计模式下的同步&异步日志系统测试报告
服务器·c++·vscode·设计模式
geovindu1 天前
go:Decorator Pattern
开发语言·设计模式·golang·装饰器模式