Java设计模式-命令模式

本文探讨了设计模式中的命令模式,旨在实现请求者与执行者之间的解耦。通过一个具体的例子——遥控器控制电器的开关,阐述了命令模式的应用。文章还附带了相关的UML类图和Java实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

15、命令模式

命令模式就是将“动作的请求者”从“动作的执行者”对象中解耦。

具体示例:遥控器可以操控多个电器,每个电器有开和关两个按钮(分别对应开和关命令)。

UML类图:

在这里插入图片描述

Java代码:

// 命令接口
public interface Command {
    void execute();
}

// 开灯命令
public class LightOnCommand implements  Command {
    Light light;

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

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

// 关灯命令
public class LightOffCommand implements Command {
    Light light;

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

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

// 灯
public class Light {
    public void on(){
        System.out.println("开灯了");
    }

    public void off(){
        System.out.println("关灯了");
    }
}

// 遥控器
public class RemoteController {
    //打开命令
    Command[] onCommands;
    //关闭命令
    Command[] offCommands;

    public RemoteController() {
        this.onCommands = new Command[5];
        this.offCommands = new Command[5];
    }

    // 为第no个按钮设置命令
    public void setCommands(int no,Command onCommand,Command offCommand){
        onCommands[no] = onCommand;
        offCommands[no] = offCommand;
    }

    // 按第no个的打开按钮
    public void pushOnButton(int no){
        onCommands[no].execute();
    }

    // 按第no个的关闭按钮
    public void pushOffButton(int no){
        offCommands[no].execute();
    }
}

public class Test320 {
    public static void main(String[] args) {
        Light light = new Light();
        LightOffCommand lightOffCommand = new LightOffCommand(light);
        LightOnCommand lightOnCommand = new LightOnCommand(light);
        RemoteController remoteController = new RemoteController();
        remoteController.setCommands(0,lightOnCommand,lightOffCommand);
        remoteController.pushOnButton(0);
        remoteController.pushOffButton(0);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值