设计模式学习笔记十五:命令模式
2015-08-25 23:34
351 查看
介绍
命令模式,Command模式,属于对象行为模式。将“请求”封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象。命令模式也支持可撤消的操作。UML结构图:
场景模拟
本例是模拟实现一个遥控器。代码实现
1.先模拟两个真正干活的对象,即invoker:public class Light{ public void on() { System.out.println("light is on"); } public void off() { System.out.println("light is off"); } } public class TV { public void on() { System.out.println("TV is on"); } public void off() { System.out.println("TV is off"); } }
2.定义统一命令调用接口,即Command(刚开始用Runnable来着,偷懒:]):
public interface Command { public void execute(); }
3.定义开关命令,统一实现Command接口,即ConcreteCommand:
public class LightOnCommand implements Command { private Light light; public LightOnCommand(Light light) { this.light = light; } @Override public void execute() { light.on(); } } public class LightOffCommand implements Command { private Light light; public LightOffCommand(Light light) { this.light = light; } @Override public void execute() { light.off(); } }
4.定义操作控制对象,即Receiver:
public class RemoteControl { Command[] onCommands; Command[] offCommands; public RemoteControl() { onCommands = new Command[2]; offCommands = new Command[2]; } public void setOnCommand(int slot, Command onCommand, Command offCommand) { onCommands[slot] = onCommand; offCommands[slot] = offCommand; } public void onButtonWasPushed(int slot) { onCommands[slot].execute(); } public void offButtonWasPushed(int slot) { offCommands[slot].execute(); } }
5.调用,即Client:
public class RemoteLoader { public static void main(String[] args) { RemoteControl control = new RemoteControl(); Light light = new Light(); TV tv = new TV(); // 加载命令 control.setOnCommand(0, new LightOnCommand(light), new LightOffCommand(light)); control.setOnCommand(1, new TVOnCommand(tv), new TVOffCommand(tv)); // 执行命令 control.onButtonWasPushed(0); control.offButtonWasPushed(0); System.out.println(); control.onButtonWasPushed(1); control.offButtonWasPushed(1); } }
相关文章推荐
- 链接属性和存储类型
- Linux系统磁盘管理基本知识
- 不带signed或unsigned关键字的char型 无符号数? 有符号数? C标准规定为 Implementation Defined !!!
- Effective C++——条款1和条款2(第1章)
- lesson2-java虚拟机之jvm结构
- GCD总结
- Tween动画
- CSS学习------之简单图片切换
- 大分享-hibernate,springmvc,easyui简要介绍
- C#解析HTML
- 图像处理形态学椭圆形模板结构元素的设计与实现
- find、sed、awk
- 读写锁
- Linux磁盘分区管理--ext2和ext3文件系统逻辑结构分析
- android toolku
- ThreadLocal维护线程局部 变量或线程局部对象
- 有了jsRender,妈妈再也不用担心我用jq拼接DOM拼接的一团糟了、页面整齐了、其他伙伴读代码也不那么费劲了
- 2015-8-25关于学习方法(控件)
- 算法学习 - 最长公共子序列(LCS)C++实现
- CS,九,十,十一,十二