// ConcreteCommand - 具体命令类 - 篇幅问题只实现前两个 // 打开电视机 public class TVOpenCommand implements Command { private Televition tv; public TVOpenCommand(Televition tv) { this.tv = tv; } public void execute () { this.tv.open(); } }
// 关闭电视机 public class TVCloseCommand implements Command { private Televition tv; public TVCloseCommand(Televition tv) { this.tv = tv; } public void execute() { this.tv.close(); } }
// 空命令 - 利用空命令取代null确保运行时的安全 public class NoCommand implements Command { public void execute() { System.out.println("No command here"); } }
// Invoker - 调用者 public class Controller { private Command[] commands; private static final int length = 7; public Controller() { commands = new Command[length]; for (int i = 0; i < length; i++) { commands[i] = new NoCommand(); } } public setCommand(int index, Command command) { commands[index] = command; } public void pushButton(int index) { commands[index].execute(); } }
// Receiver - 接受者 public class Television { public Television() { ; } public void on() { System.out.println("Television is on now!"); } public void off() { System.out.println("Television is off now!"); } }
// Client - 客户类 public class Client { public static void main(String[] args) { Television tv = new Television(); TVOpenCommand tvOpen = new TVOpenCommand(tv); TVCloseCommand tvClose = new TVOCloseCommand(tv); Controller controller = new Controller(); controller.setCommand(0, tvOpen); controller.setCommand(1, tvClose); controller.pushButton(0); controller.pushButton(1); } }