设计模式——命令模式

命令模式是一种行为设计模式,它把请求封装成对象,从而能够参数化方法调用、延迟调用执行、以及支持可撤销的操作。这种模式在很多情况下都非常有用,尤其是在需要将请求发送者和请求接收者解耦的情况下。

命令模式的基本概念

  1. 命令接口 (Command): 定义了所有命令都需要实现的一个公共接口。
  2. 具体命令 (ConcreteCommand): 实现命令接口,通常包含对接受者的引用。
  3. 接受者 (Receiver): 实现了命令所要执行的操作。
  4. 调用者 (Invoker): 请求命令来执行一个特定操作。

命令模式的结构

  • Command (命令接口)
    • execute(): 执行命令的方法。
  • ConcreteCommand (具体命令)
    • 包含接收者对象,并实现execute()方法。
  • Receiver (接收者)
    • 包含实际业务逻辑的方法。
  • Invoker (调用者)
    • 持有一个命令对象,并通过setCommand(Command command)设置命令,通过action()调用命令的execute()方法。

示例代码

有一个简单的遥控器和一些电器设备作为例子。

接收者(Receiver)
public class Light {
    public void on() {
        System.out.println("Light is on");
    }

    public void off() {
        System.out.println("Light is off");
    }
}
命令接口(Command)
public interface Command {
    void execute();
}
具体命令(ConcreteCommand)
public class LightOnCommand implements Command {
    private Light light;

    public LightOnCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.on();
    }
}

public class LightOffCommand implements Command {
    private Light light;

    public LightOffCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.off();
    }
}
调用者(Invoker)
public class RemoteControl {
    private Command command;

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

    public void pressButton() {
        command.execute();
    }
}
客户端代码
public class Main {
    public static void main(String[] args) {
        Light livingRoomLight = new Light();
        Command lightOn = new LightOnCommand(livingRoomLight);
        Command lightOff = new LightOffCommand(livingRoomLight);

        RemoteControl remoteControl = new RemoteControl();

        // Turn the light on
        remoteControl.setCommand(lightOn);
        remoteControl.pressButton();

        // Turn the light off
        remoteControl.setCommand(lightOff);
        remoteControl.pressButton();
    }
}

使用场景

  • 解耦:当需要将请求发送者和接收者解耦时。
  • 可撤销/重做:当需要支持请求的撤销和重做操作时。
  • 事务处理:当一组操作必须全部成功或者全部失败时。
  • 队列化:当需要将请求放入队列中,稍后处理时。
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值