1、例子
3、代码
- public class RemoteController {
-
- //开 按钮的命令数组
- Command[] onCommands;
- Command[] offComands;
-
- //执行撤销的命令
- Command undoCommand;
-
- //构造器,完成对按钮的初始化
-
-
- public RemoteController() {
-
- onCommands=new Command[5];
- offComands=new Command[5];
-
- for (int i = 0; i < 5; i++) {
- onCommands[i]=new NoCommand();
- offComands[i]=new NoCommand();
- }
- }
- //给我们的按钮设置你需要的命令
- public void setCommand(int no,Command onCommand,Command offComand){
- onCommands[no]=onCommand;
- offComands[no]=offComand;
- }
-
- //按下开按钮
- public void onButtonWasPushed(int no){
- onCommands[no].execute();
- undoCommand=onCommands[no];
- }
-
- //按下开按钮
- public void offButtonWasPushed(int no){
- offComands[no].execute();
- undoCommand=offComands[no];
- }
-
- //按下撤销按钮
- public void undoButtonWasPushed(){
-
- undoCommand.undo();
- }
-
- }
- public class LightOnCommand implements Command {
-
- //聚合LightReceiver
- LightReceiver light;
-
- //构造器
-
-
- public LightOnCommand(LightReceiver light) {
- this.light = light;
- }
-
- @Override
- public void execute() {
- light.on();
- }
-
- @Override
- public void undo() {
- light.off();
- }
- }
- public class LightOffCommand implements Command {
-
- //聚合LightReceiver
- LightReceiver light;
-
- //构造器
-
-
- public LightOffCommand(LightReceiver light) {
- this.light = light;
- }
-
-
- @Override
- public void execute() {
- light.off();
- }
-
- @Override
- public void undo() {
- light.on();
- }
- }
- public interface Command {
- public void execute();
- public void undo();
- }
- public class LightReceiver {
-
- public void on(){
- System.out.println("电灯打开了");
- }
-
- public void off(){
- System.out.println("电灯关闭了");
- }
- }
- public class Client {
- public static void main(String[] args) {
- LightReceiver lightReceiver = new LightReceiver();
-
- LightOnCommand lightOnCommand = new LightOnCommand(lightReceiver);
- LightOffCommand lightOffCommand = new LightOffCommand(lightReceiver);
-
- RemoteController remoteController = new RemoteController();
-
- remoteController.setCommand(0,lightOnCommand,lightOffCommand);
- System.out.println("开始");
- remoteController.onButtonWasPushed(0);
- System.out.println("关闭");
- remoteController.offButtonWasPushed(0);
- System.out.println("撤销");
- remoteController.undoButtonWasPushed();
-
-
- System.out.println("___________________");
-
- TVReceiver tvReceiver = new TVReceiver();
-
- TVOffCommand tvOffCommand = new TVOffCommand(tvReceiver);
- TVOnCommand tvOnCommand = new TVOnCommand(tvReceiver);
-
-
- remoteController.setCommand(1,tvOnCommand,tvOffCommand);
-
-
-
- System.out.println("开始");
- remoteController.onButtonWasPushed(1);
- System.out.println("关闭");
- remoteController.offButtonWasPushed(1);
- System.out.println("撤销");
- remoteController.undoButtonWasPushed();
-
-
-
- }
- }
总结:把逻辑流程抽象,底部实现类,改为插拔式