命令模式就是把方法调用封装起来,将动作请求者和动作实行者隔离开。
public class RemoteControl {
List<Command> onCommands;
List<Command> offCommands;
public RemoteControl(){
onCommands=new ArrayList<>();
offCommands=new ArrayList<>();
}
public void addCommand(Command onCommand,Command offCommand){
onCommands.add(onCommand);
offCommands.add(offCommand);
}
public void onButtonWasPushed(int slot){
onCommands.get(slot).execute();
}
public void offButtonWasPushed(int slot){
offCommands.get(slot).execute();
}
public String toString(){
return "";
}
}
命令
public interface Command {
void execute();
void undo();
}
public class LightOffCommand implements Command {
Light light;
public LightOffCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.off();
}
@Override
public void undo() {
}
}
public class Light {
public void on() {
}
public void off() {
}
}
具体命令中控制目标的行为