命令模式应用场景
比如有个这样的场景,一个控制器,上面有很多对按钮,一对按钮包括开和关,然后这个可以将一些电器插在这个上面,然后就可以通过这个控制器来进行控制相应的电器。如果以后类似于需要模拟这种场景,你可以参考下这种模式。
命令模式使用步骤
1.定义一个命令接口,所有命令都需要是现在这个接口,其主要方法有execute,即执行命令。
public interface Command { public void execute();}
2.定义一个电器接口,所有电器实现这个接口,方法主要是有on和off,即打开和关闭。
public interface Device { public void on(); public void off();}
3.编写一些接口实现类,如灯泡、收音机等及其相关命令实现类
//Light.javapublic class Light implements Device { private String deviceName; public Light() { deviceName = "Light"; } @Override public void on() { System.out.println(deviceName + " is twinkling"); } @Override public void off() { System.out.println(deviceName + " is off"); }}//Radio.javapublic class Radio implements Device { private String deviceName; public Radio() { deviceName = "radio"; } @Override public void on() { System.out.println(deviceName + "is working"); } @Override public void off() { System.out.println(deviceName + "is over"); }}//CommandOn.javapublic class CommandOn implements Command { private Device device; public CommandOn(Device device) { this.device = device; } @Override public void execute() { device.on(); }}//CommandOff.javapublic class CommandOff implements Command { private Device device; public CommandOff(Device device) { this.device = device; } @Override public void execute() { device.off(); }}
4.编写控制器
public class RemoteController { private Command[] commandsOn; private Command[] commandsOff; public RemoteController() { commandsOn = new Command[7]; commandsOff = new Command[7]; } public void setCommand(int index, Command on, Command off) { commandsOn[index] = on; commandsOff[index] = off; } public void onButton(int index) { if (commandsOn[index] != null) commandsOn[index].execute(); } public void offButton(int index) { if (commandsOff[index] != null) commandsOff[index].execute(); }}
测试代码
public class Test { public static void main(String[] args) { RemoteController remoteController = new RemoteController(); Light light = new Light(); Radio radio = new Radio(); remoteController.setCommand(0, new CommandOn(light), new CommandOff(light)); remoteController.onButton(0); remoteController.offButton(0); remoteController.setCommand(0, new CommandOn(radio), new CommandOff(radio)); remoteController.onButton(0); remoteController.offButton(0); }}
如果你对这篇博客有什么建议或者疑问可以留言哦>V<