设计模式之命令模式 Command

模式之命令模式

1)先创建一个command接口,里面只有一个execute() 方法等待实现

public interface Command {
    void execute();
}

2)创建一个灯类作为demo

package design.mode.command;

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

    public void off() {
        System.out.println("light off now");
    }
}

  1. 根据Light 类作为构造函数参数,创建两个命令类LightOnCommand、LightOffCommand。命令模式的设计思路是 需要这两个命令类要实现Command接口。
public class LightOnCommand implements Command{
    Light light;

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

    @Override
    public void execute() {
        light.on();
    }
}
public class LightOffCommand implements Command{
    Light light;

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

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

4)设计一个命令调度类 RemoteCtl,用于调度命令、执行命令。依赖于实现了Command接口的命令类如LightOnCommand

public class RemoteCtl {
    Command command;

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

    public void execute(){
        command.execute();
    }
}

5)Main函数调用展示,命令模式的执行流程

public class CommandMain {
    public static void main(String[] args) {
        //new Light
        Light light = new Light();
        //new RemoteCtl
        RemoteCtl remoteCtl = new RemoteCtl();
        //light on
        LightOnCommand lightOnCommand = new LightOnCommand(light);
        remoteCtl.setCommand(lightOnCommand);
        remoteCtl.execute();
        //light off
        LightOffCommand lightOffCommand = new LightOffCommand(light);
        remoteCtl.setCommand(lightOffCommand);
        remoteCtl.execute();
    }
}

6)执行结果展示

light on now
light off now
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值