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

命令模式(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();
    }
}
相关推荐
Supersist4 小时前
【设计模式03】使用模版模式+责任链模式优化实战
后端·设计模式·代码规范
geovindu5 小时前
go: Interpreter Pattern
开发语言·设计模式·golang·解释器模式
workflower6 小时前
从拿订单到看方向
大数据·人工智能·设计模式·机器人·动态规划
sensen_kiss10 小时前
CPT304 SoftwareEngineeringII 软件工程 2 Pt.3 设计模式(上)
设计模式·软件工程
mit6.82410 小时前
20种Agent 设计模式
人工智能·设计模式
workflower10 小时前
企业酝酿数智化内驱力
大数据·人工智能·设计模式·机器人·动态规划
likerhood10 小时前
java设计模式 · 适配器模式 (Adapter Pattern)
java·设计模式·适配器模式
蜡笔小马12 小时前
04.C++设计模式-桥接模式
c++·设计模式·桥接模式
geovindu12 小时前
go:Condition Variable Pattern
开发语言·后端·设计模式·golang·条件变量模式
geovindu13 小时前
Python: Condition Variable Pattern
开发语言·python·设计模式·条件变量模式