需求:现有一个遥控器,有七个可编程的插槽,每个插槽都对应开关按钮,遥控器还具备一个整体的撤销按钮。
可控装置:电灯、风扇、热水器、音响设备和其它类似的可控制装备。要求能够控制目前的装置和任何未来可能出现的装置。
我们把这个过程想象成餐厅吃饭的过程:顾客根据菜单点单,然后将订单给服务员,服务员将订单放到厨房柜台上,厨师拿到订单进行执行,制作出美味的饭菜。
在这里,遥控器就是一个远程控制,它掌握一系列的命令接口,当我们按下遥控器按钮时,发出相应的命令进行执行,相应的命令对象接收到执行命令后发送命令给具体执行者,具体执行者收到命令并执行相应的行文。这就达到了请求者与具体执行者解耦的目的。
首先把问题简化,假设我们只有一个遥控器,它只有一个按钮和对应的插槽,可以控制一个装置。
设计图如下:
实现代码如下:
远程控制类SimpleRemoteControl :
public class SimpleRemoteControl { Command slot; public SimpleRemoteControl(){} public Command getSlot() { return slot; } public void setSlot(Command slot) { this.slot = slot; } public void buttonWasPressed() { slot.execute(); } }
命令接口Command:
public interface Command { public void execute(); }
具体命令类:
灯泡开命令类LightOnCommand:
public class LightOnCommand implements Command{ Light light; public LightOnCommand(Light light) { this.light=light; } @Override public void execute() { // TODO Auto-generated method stub light.on(); } }
灯泡关命令类:
public class LightOffCommand implements Command{ Light light; public LightOffCommand(Light light) { this.light=light; } @Override public void execute() { // TODO Auto-generated method stub light.off(); } }
车门开命令类:
public class GargeDoorOpenCommand implements Command{ GargeDoor gargeDoor; public GargeDoorOpenCommand(GargeDoor gargeDoor) { this.gargeDoor=gargeDoor; } @Override public void execute() { // TODO Auto-generated method stub gargeDoor.open(); } }
车门关命令类:
public class GargeDoorCloseCommand implements Command{ GargeDoor gargeDoor; public GargeDoorCloseCommand(GargeDoor gargeDoor) { this.gargeDoor=gargeDoor; } @Override public void execute() { // TODO Auto-generated method stub gargeDoor.close(); } }
最后接收执行者类:
灯泡:
public class Light { public void on() { System.out.println("light is on"); } public void off() { System.out.println("light is close"); } }
车门:
public class GargeDoor { public void open() { System.out.println("door is open"); } public void close() { System.out.println("door is close"); } }
测试类:
public class RemoteControlTest { public static void main(String[] args) { SimpleRemoteControl remote=new SimpleRemoteControl(); Light light=new Light(); LightOnCommand lightOn=new LightOnCommand(light); remote.setSlot(lightOn); remote.buttonWasPressed(); GargeDoor gargeDoor=new GargeDoor(); GargeDoorOpenCommand gargeDoorOpen=new GargeDoorOpenCommand(gargeDoor); remote.setSlot(gargeDoorOpen); remote.buttonWasPressed(); } }