package com.tc.order;

 

 

/**命令模式  就是发出命令的对象与执行命令的对象解耦。两者通过中介者传递,命令封装了接收者以及

 * 要执行的n个动作中介者不需要知道传递的对象信息。命令可以撤销,如下面的undo()

 * 命令接口

 */

public interface Command {

/**

* 执行命令

*/

public void execute();

/**

* 回滚操作

*/

public void undo();

}

 

package com.tc.order;

 //要操作的对象

public class Light {

public void on() {

System.out.println("the light is on.");

}

 

public void off() {

System.out.println("the light is off.");

}

}

 

package com.tc.order;

 //关灯操作命令

public class LightOffCommand implements Command {

private Light light;

 

public LightOffCommand(Light light) {

this.light = light;

}

 

@Override

public void execute() {

light.off();

}

 

@Override

public void undo() {

light.on();

}

}

 

package com.tc.order;

 //开灯操作命令

public class LightOnCommand implements Command {

private Light light;

 

public LightOnCommand(Light light) {

this.light = light;

}

 

@Override

public void execute() {

light.on();

}

 

@Override

public void undo() {

light.off();

}

}

 

package com.tc.order;

 

import java.util.ArrayList;

import java.util.List;

 

/**

 * 遥控器类

 */

public class RemoteControl {

private List<Command> onCommands;

private List<Command> offCommands;

private Command undoCommand;

 

public RemoteControl() {

onCommands = new ArrayList<Command>();

offCommands = new ArrayList<Command>();

}

 

public void setCommand(int index, Command onCommand, Command offCommand) {

int size = onCommands.size();

if (size == index) {

onCommands.add(null);

offCommands.add(null);

} else if (size < index) {

throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); 

}

onCommands.set(index, onCommand);

offCommands.set(index, offCommand);

}

 

public void onButtonWasPushed(int index) {

Command command = onCommands.get(index);

command.execute();

undoCommand = command;

}

 

public void offButtonWasPushed(int index) {

Command command = offCommands.get(index);

command.execute();

undoCommand = command;

}

 

public void undoButtonWasPushed() {

if (null == undoCommand) {

throw new IllegalArgumentException("can not undo."); 

}

undoCommand.undo();

}

}

 

package com.tc.order;

 //测试类

public class Test1 {

public static void main(String[] args) {

Light light = new Light();

 

LightOnCommand lightOnCommand = new LightOnCommand(light);

LightOffCommand lightOffCommand = new LightOffCommand(light);

 

RemoteControl remoteControl = new RemoteControl();

remoteControl.setCommand(0, lightOnCommand, lightOffCommand);

remoteControl.offButtonWasPushed(0);

 

remoteControl.undoButtonWasPushed();

}

}

posted on 2016-08-30 17:04  反光的小鱼儿  阅读(354)  评论(0编辑  收藏  举报