python
2015-10-28 22:42
786 查看
上篇介绍了命令模式的理论知识,这里再写两个小例子,加深理解。
1、撤销命令,关键在于命令执行的时侯保存这个命令对象,这就是把操作封装成对象的好处。
测试:
输出:
这里模拟的是简单操作,实际上可能有针对Light状态值的操作,但实现原理是一样的。
2、宏命令:创建一个新类MacroCommand,封装多个命令,达到一次性执行多个命令的目的。
执行结果是:
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...
相关文章推荐
- Python拷贝及多进程与类的问题
- 由python代码生成UML类图
- 运行第一个python程序
- 决策树算法 生成 剪枝 in Python
- Python中变量作用域问题——局部变量与全局变量
- python学习笔记(八)列表生成式
- Notes on Generator 2
- python字符串连接,截取,替换操作
- Python线程指南
- k近邻法 kNN算法 in Python
- python学习记录之1028
- Python的排序
- Python算法:动态规划
- Python多进程
- pythony文件操作编码问题
- [LeetCode]题解(python):035-Search Insert Position
- python模块之codecs
- 【Python】python-一个class继承的小case
- [LeetCode]题解(python):034-Search for a Range
- [LeetCode]题解(python):033-Search in Rotated Sorted Array