设计模式学习笔记——命令模式
2017-05-25 21:42
375 查看
命令模式:将“请求”封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象。命令模式也支持可撤销的操作。
实现命令接口
目标类以及命令封装
实现一个空命令
遥控器类
Client
输出结果如下:
Living Room Light is on!
Living Room Light is off!
Living Room Light is on!
实现命令接口
public interface Command { public void execute(); public void undo(); }
目标类以及命令封装
public class Light { private String name; public Light(String name) { this.name = name; } public void on(){ System.out.println(name+" Light is on!"); } public void off(){ System.out.println(name+" Light is off!"); } }
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 LightOffCommand implements Command { Light light; public LightOffCommand(Light light) { this.light = light; } public void execute() { light.off(); } public void undo() { light.on(); } }
实现一个空命令
public class NoCommand implements Command { public void execute() {} }
遥控器类
public class RemoteControl { Command[] onCommands; Command[] offCommands; Command undoCommand; // 前一个命令 public RemoteControl() { onCommands = new Command[6]; offCommands = new Command[6]; Command noCommand = new NoCommand(); for(int i = 0; i < 6; i++) { onCommands[i] = noCommand; offCommands[i] = noCommand; } undoCommand = noCommand; } public void setCommand(int pos, Command onCommand, Command offCommand) { onCommands[pos] = onCommand; offCommands[pos] = offCommand; } public void onButtonWasPushed(int pos) { onCommands[pos].execute(); undoCommand = onCommands[pos]; } public void offButtonWasPushed(int pos) { offCommands[pos].execute(); undoCommand = offCommands[pos]; } public void undoButtonWasPushed() { undoCommand.undo(); } }
Client
public class Client { public static void main(String[] args) { RemoteControl remoteControl = new RemoteControl(); Light livingRoomLight = new Light("Living Room"); LightOnCommand livingRoomLightOn = new LightOnCommand(livingRoomLight); LightOffCommand livingRoomLightOff = new LightOffCommand(livingRoomLight); remoteControl.setCommand(0, livingRoomLightOn, livingRoomLightOff); remoteControl.onButtonWasPushed(0); remoteControl.offButtonWasPushed(0); remoteControl.undoButtonWasPushed(); } }
输出结果如下:
Living Room Light is on!
Living Room Light is off!
Living Room Light is on!
相关文章推荐
- 《Head First 设计模式》学习笔记: 命令模式
- 设计模式学习笔记——命令模式
- 设计模式学习笔记——命令模式
- 设计模式学习笔记(一)——面向对象设计模式与原则
- [设计模式学习笔记之一]面向对象是什么?
- 设计模式学习笔记(二)——Singleton单件模式
- 设计模式学习笔记(一)
- 设计模式学习笔记(一)
- 面向对象的设计模式的学习笔记,不断学习归纳总结ing
- 设计模式学习笔记(1)
- J2EE设计模式学习笔记之--实际的数据存取
- 设计模式学习笔记(4)
- 设计模式学习笔记(三)——Abstract Factory抽象工厂模式
- 设计模式学习笔记(三)
- 设计模式学习笔记1:对设计模式学习的一点想法兼谈Facade模式
- 设计模式学习笔记(2)
- 设计模式学习笔记2:说说Mediator模式
- 设计模式的学习笔记!(一)
- C#设计模式学习笔记---简单工厂模式
- [设计模式学习笔记之二]设计模式和量体剪衣