参考链接:http://www.runoob.com/design-pattern/command-pattern.html
命令模式(Command Pattern)是一种数据驱动的设计模式,它属于行为型模式。
理论介绍
命令模式将请求封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象。命令模式也支持可撤销的操作。
请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令。
应用场景
在某些场合,比如要对行为进行"记录、撤销 or 重做、事务"等处理,这种无法抵御变化的紧耦合是不合适的。在这种情况下,如何将"行为请求者"与"行为实现者"解耦?将一组行为抽象为对象,可以实现二者之间的松耦合。
代码实现参考
1.实现命令接口
package command_pattern;
/**
* 命令接口
*/
public interface Command {
public void execute();
}
2.实现一个打开电灯的开关
package command_pattern;
/**
* 实现一个打开电灯的命令
* 将请求封装成对象
*/
public class LightOnCommand implements Command {
Light light;
public LightOnCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
//命令对象将动作和接收者包进对象
light.on();
}
}
3.实现一个关闭电灯的命令
package command_pattern;
/**
* 实现一个关闭电灯的命令
* 将请求封装成对象
*/
public class LightOffCommand implements Command {
Light light;
public LightOffCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
//命令对象将动作和接收者包进对象
light.off();
}
}
4.实现遥控器
package command_pattern;
public class RemoteControl {
Command[] onCommands;
Command[] offCommands;
public RemoteControl() {
onCommands = new Command[7];
offCommands = new Command[7];
Command noCommand = new NoCommand();
for (int i = 0; i < 7; i++){
onCommands[i] = noCommand;
offCommands[i] = noCommand;
}
}
public void setCommand(int slot, Command onCommand, Command offCommand){
onCommands[slot] = onCommand;
offCommands[slot] = offCommand;
}
public void onButtonWasPushed(int slot){
if (onCommands[slot] != null){
onCommands[slot].execute();
}
}
public void offButtonWasPushed(int slot){
offCommands[slot].execute();
}
public String toString(){
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("\n----- Remote Control ------\n");
for (int i = 0; i < onCommands.length; i++){
stringBuffer.append("[Slot " + i + " ]" + onCommands[i].getClass().getName() +
" " + onCommands[i].getClass().getName() + "\n");
}
return stringBuffer.toString();
}
}
5.模拟测试遥控器
package command_pattern;
/**
* 模拟命令模式的客户
*/
public class RemoteControlTest {
public static void main(String[] args) {
SimpleRemoteControl remoteControl = new SimpleRemoteControl();
Light light = new Light();
//创建一个命令,将接收者传给他
LightOnCommand command = new LightOnCommand(light);
remoteControl.setCommand(command);
remoteControl.buttonWasPressed();
System.out.println("----------STOP & NEXT----------");
RemoteControl control = new RemoteControl();
LightOnCommand lightOn = new LightOnCommand(light);
LightOffCommand lightOff = new LightOffCommand(light);
control.setCommand(1, lightOn, lightOff);
System.out.println(control);
control.onButtonWasPushed(1);
control.offButtonWasPushed(1);
}
}
补充
- 优点
- 降低了系统耦合度
- 新的命令很容易添加到系统中
- 缺点
- 使用命令模式可能会导致某些系统有过多的具体命令类