1.应用场景
如果一个遥控器拥有多个按钮,每个按钮可以控制开或者关,但是可以动态设置控制不同的组件(比如电视,冰箱等)。
2.这时可以对每一个组件建立相应的命令,并将这些命令动态的设置进遥控器
3.代码实现
遥控器类
public class RemoteController{
private Command[] command;
//如果使用栈则可以从最后开始undo或者do操作(可以用于取消操作),用队列则可以从最前面的操作开始执行undo操作(可以用于系统还原后的恢复)
public BlockingQueue<command> undo;
public RemoteController(int slotCount){
command = new Command[slotCount];
undo = new ArrayBlockingQueue<command>(slotCount);
}
public void execute(){
command.execute();
}
public void redoAllOperation(){
while(undo.peek() != null){
((Command) undo.pop()).execute();
}
}
public setCommand(int slot, Command command){
this.command[slot] = command;
}
}
灯泡类
public class Light{
private int state = 0;//默认关闭
//get set
public void on(){
state = 1;
System.out.println("This Light is on");
}
public void off(){
state = 0;
System.out.println("This Light is off");
}
}
命令接口
public interface Command{
void execute();
void undo();
}
灯泡命令
public class LightCommand implements Command{
private Light light;
//get set
public LightCommand(Light light){
this.light = light;
}
public void execute(){
if(light.getState() == 0){
light.on();
}
else{
light.off();
}
}
//这儿undo和execute()方法一样
public void undo(){
if(light.getState() == 0){
light.on();
}
else{
light.off();
}
}
}