设计模式学习笔记十五:命令模式

本文介绍了命令模式在实现遥控器控制功能中的应用,通过定义命令接口、具体命令和接收者对象,实现了不同设备的开关控制。此外,文章还展示了如何通过操作控制对象来调用这些命令,以及命令模式支持的可撤销操作特性。

介绍

命令模式,Command模式,属于对象行为模式。将“请求”封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象。命令模式也支持可撤消的操作。

UML结构图:

Command

场景模拟

本例是模拟实现一个遥控器。

代码实现

1.先模拟两个真正干活的对象,即invoker:

public class Light{
    public void on() {
        System.out.println("light is on");
    }
    public void off() {
        System.out.println("light is off");
    }
}

public class TV {
    public void on() {
        System.out.println("TV is on");
    }
    public void off() {
        System.out.println("TV is off");
    }
}

2.定义统一命令调用接口,即Command(刚开始用Runnable来着,偷懒:]):

public interface Command {
    public void execute();
}

3.定义开关命令,统一实现Command接口,即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();
    }
}

4.定义操作控制对象,即Receiver:

public class RemoteControl {
    Command[] onCommands;
    Command[] offCommands;
    public RemoteControl() {
        onCommands = new Command[2];
        offCommands = new Command[2];
    }
    public void setOnCommand(int slot, Command onCommand, Command offCommand) {
        onCommands[slot] = onCommand;
        offCommands[slot] = offCommand;
    }
    public void onButtonWasPushed(int slot) {
        onCommands[slot].execute();
    }
    public void offButtonWasPushed(int slot) {
        offCommands[slot].execute();
    }

}

5.调用,即Client:

public class RemoteLoader {
    public static void main(String[] args) {
        RemoteControl control = new RemoteControl();
        Light light = new Light();
        TV tv = new TV();

        // 加载命令
        control.setOnCommand(0, new LightOnCommand(light), new LightOffCommand(light));
        control.setOnCommand(1, new TVOnCommand(tv), new TVOffCommand(tv));

        // 执行命令
        control.onButtonWasPushed(0);
        control.offButtonWasPushed(0);

        System.out.println();

        control.onButtonWasPushed(1);
        control.offButtonWasPushed(1);
    }
}

转载于:https://www.cnblogs.com/liushijie/p/4759032.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值