

/***
* @author shaofan
* @Description
*/
public class HouseApp {
public static void main(String[] args) {
RemoteController controller = new RemoteController();
Command lightOnCommand = new LightOnCommand(new LightReceiver());
Command lightOffCommand = new LightOffCommand(new LightReceiver());
controller.setCommand(0,lightOnCommand,lightOffCommand);
controller.onButtonPushed(0);
controller.offButtonPushed(0);
controller.undoButtonPushed();
}
}
class RemoteController{
Command[] onCommand;
Command[] offCommand;
Command undoCommand;
public RemoteController(){
onCommand = new Command[5];
offCommand = new Command[5];
for (int i = 0; i < 5; i++) {
onCommand[i] = new NoCommand();
offCommand[i] = new NoCommand();
}
}
public void setCommand(int no,Command onCommand,Command offCommand){
this.onCommand[no] = onCommand;
this.offCommand[no] = offCommand;
}
public void onButtonPushed(int no){
onCommand[no].execute();
// 每个按钮执行之后,将撤销按钮刷新,如果要调用撤销按钮则可以撤销上一次的操作
undoCommand = onCommand[no];
}
public void offButtonPushed(int no){
offCommand[no].execute();
undoCommand = offCommand[no];
}
public void undoButtonPushed(){
undoCommand.undo();
}
}
interface Command{
/**
* 执行
*/
void execute();
/**
* 撤销
*/
void undo();
}
class LightOnCommand implements Command{
LightReceiver lightReceiver;
public LightOnCommand(LightReceiver lightReceiver){
this.lightReceiver = lightReceiver;
}
@Override
public void execute() {
lightReceiver.on();
}
@Override
public void undo() {
lightReceiver.off();
}
}
class LightOffCommand implements Command{
LightReceiver lightReceiver;
public LightOffCommand(LightReceiver lightReceiver){
this.lightReceiver = lightReceiver;
}
@Override
public void execute() {
lightReceiver.off();
}
@Override
public void undo() {
lightReceiver.on();
}
}
/***
* 没有任何接收者,空执行所有命令,当调用空命令什么也不做,省去了对空的判断
*/
class NoCommand implements Command{
@Override
public void execute() {
}
@Override
public void undo() {
}
}
class LightReceiver{
void on(){
System.out.println("light on");
}
void off(){
System.out.println("light off");
}
}