上篇介绍了命令模式的理论知识,这里再写两个小例子,加深理解。
1、撤销命令,关键在于命令执行的时侯保存这个命令对象,这就是把操作封装成对象的好处。
//这个不变 public class Light { public void off(){ System.out.println("off..."); } public void on(){ System.out.println("on..."); } } //Command接口添加一个undo() public interface Command { public void execute(); public void undo(); } public class LightOffCommand implements Command { Light light; public LightOffCommand(Light light){ this.light = light; } public void execute() { light.off(); } //在这里进行之前操作的逆操作,实现“撤销” public void undo(){ light.on(); } } public class LightOnCommand implements Command { Light light; public LightOnCommand(Light light){ this.light = light; } public void execute() { light.on(); } public void undo(){ light.off(); } } public class RemoteControl { Command c; Command lastCommand; public void setCommand(Command c){ this.c = c; } public void pressButton(){ c.execute(); //保存命令对象的引用 lastCommand = c; } public void undoPressButton(){ lastCommand.undo(); } }
测试:
public class CommandLoader { public static void main(String[] args) { RemoteControl src = new RemoteControl(); Light light = new Light(); LightOnCommand lo = new LightOnCommand(light); src.setCommand(lo); //操作 src.pressButton(); System.out.println(); //撤销操作 src.undoPressButton(); } }
输出:
on... off...
这里模拟的是简单操作,实际上可能有针对Light状态值的操作,但实现原理是一样的。
2、宏命令:创建一个新类MacroCommand,封装多个命令,达到一次性执行多个命令的目的。
//此类与一般的具体命令是一个级别的 public class MacroCommand implements Command{ //保存多个命令对象 Command[] commands; public MacroCommand(Command[] commands) { this.commands = commands; } public void execute(){ for (Command c : commands) { c.execute(); } } } public class CommandLoader { public static void main(String[] args) { //遥控器 RemoteControl rc = new RemoteControl(); //三个命令 LightOnCommand lo = new LightOnCommand(new Light()); TvOnCommand to = new TvOnCommand(new Tv()); AirConditionOnCommand ao = new AirConditionOnCommand(new AirCondition()); Command[] cs = {lo,to,ao}; //宏命令 MacroCommand mc = new MacroCommand(cs); rc.setCommand(mc); rc.pressButton(); } }
执行结果是:
on... tv on... air condition on...