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

命令模式(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();
    }
}
相关推荐
王解3 小时前
Agent Team设计模式与思维:从单体智能到群体智慧
设计模式·ai agent
geovindu5 小时前
python: Command Pattern
开发语言·python·命令模式
J_liaty5 小时前
23种设计模式一状态模式
设计模式·状态模式
Coder_Boy_12 小时前
Java高级_资深_架构岗 核心知识点全解析(模块四:分布式)
java·spring boot·分布式·微服务·设计模式·架构
资深web全栈开发1 天前
设计模式之解释器模式 (Interpreter Pattern)
设计模式·解释器模式
漠月瑾-西安1 天前
React-Redux Connect 高阶组件:从“桥梁”到“智能管家”的深度解析
react.js·设计模式·react-redux·高阶组件·connect高阶租单间·原理理解
J_liaty1 天前
23种设计模式一备忘录模式
设计模式·备忘录模式
驴儿响叮当20101 天前
设计模式之建造者模式
设计模式·建造者模式
知识即是力量ol1 天前
口语八股—— Spring 面试实战指南(终篇):常用注解篇、Spring中的设计模式
java·spring·设计模式·面试·八股·常用注解
茶本无香2 天前
【无标题】
java·设计模式·策略模式