命令模式定义:是一个高内聚的模式,将一个请求封装成一个对象,从而让你使用不同的请求把客户端参数化,对请求排队或者记录请求日志,可以提供命令的撤销和恢复操作工作。
优点:
1、类间解耦。
调用者角色与接受者角色(light)之间没有依赖,调用者只需要调用Command的exec方法,不需要知道是那一个接受者执行的。
2、可扩展性。
3、可以和其他模式结合使用。
结合责任链,实现命令族解析任务。
结合模版方法模式,可以减少Command子类的膨胀问题。
缺点:
那就是类膨胀问题。
类图如下:
代码实现如下:
light类:
package com.designpatterns.command; public class Light { public void on() { System.out.println("Light is on"); } public void off() { System.out.println("Light is off"); } }
package com.designpatterns.command; public interface Command { public Light light = new Light(); public void execute(); public void undo(); }
LightOnCommand类:
package com.designpatterns.command; public class LightOnCommand implements Command { @Override public void execute() { light.on(); } @Override public void undo() { light.off(); } }
package com.designpatterns.command; public class LightOffCommand implements Command { @Override public void execute() { light.off(); } @Override public void undo() { light.on(); } }
package com.designpatterns.command; public class NoCommand implements Command { @Override public void execute() { } @Override public void undo() { } }
package com.designpatterns.command; public class SimepleRemoteControl { private Command[] onComands; private Command[] offComands; private Command undoCommand; public SimepleRemoteControl() { onComands = new Command[7]; offComands = new Command[7]; Command noCommand = new NoCommand(); for (int i = 0; i < 7; i++) { onComands[i] = noCommand; offComands[i] = noCommand; } undoCommand = noCommand; } public void setCommand(int slot, Command onCommand, Command offCommand) { onComands[slot] = onCommand; offComands[slot] = offCommand; } public void onButtonWasPressed(int slot) { onComands[slot].execute(); undoCommand=onComands[slot]; } public void offButtonWasPressed(int slot) { offComands[slot].execute(); undoCommand=offComands[slot]; } public void undoButtonWasPushed(){ undoCommand.undo(); } }
package com.designpatterns.command; public class Main { public static void main(String[] args) { SimepleRemoteControl simepleRemoteControl = new SimepleRemoteControl(); LightOnCommand lightOnCommand = new LightOnCommand(); LightOffCommand lightOffCommand = new LightOffCommand(); simepleRemoteControl.setCommand(0, lightOnCommand, lightOffCommand); System.out.println("开灯!"); simepleRemoteControl.onButtonWasPressed(0); System.out.println("关灯!"); simepleRemoteControl.offButtonWasPressed(0); System.out.println("撤销上一步操作!"); simepleRemoteControl.undoButtonWasPushed(); } }
这就是命令模式。
参考资料:
1、设计模式之禅
2、Head First 设计模式
备注:
转载请注明出处
http://blog.csdn.net/wsyw126/article/details/51317887
by WSYW126