简介
请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的对象进行执行。命令模式是一种特殊的策略模式,体现多个策略执行的问题,而不是选择的问题
UML图
应用场景
- 界面选择、键盘、按钮、事件操作都类似命令模式
示例
电视遥控器、电视、观看电视的人
- 接收者:电视机
public class TVReceiver {
public void on() {
System.out.println("打开电视");
}
public void off() {
System.out.println("关闭电视");
}
public void changeStation() {
System.out.println("换台");
}
}
- 命令(指令):
public interface Command {
void excute();
}
public class OnCommand implements Command {
private TVReceiver tvReceiver;
public OnCommand(TVReceiver tvReceiver) {
this.tvReceiver = tvReceiver;
}
@Override
public void excute() {
System.out.println("onCommand----execute");
tvReceiver.on();
}
}
public class OffCommand implements Command {
private TVReceiver tvReceiver;
public OffCommand(TVReceiver tvReceiver) {
this.tvReceiver = tvReceiver;
}
@Override
public void excute() {
System.out.println("OffCommand----execute");
tvReceiver.off();
}
}
public class ChangeStationCommand implements Command {
private TVReceiver tvReceiver;
public ChangeStationCommand(TVReceiver tvReceiver) {
this.tvReceiver = tvReceiver;
}
@Override
public void excute() {
System.out.println("ChangeStationCommand----execute");
tvReceiver.changeStation();
}
}
- 调用者:观看者
public class Invoker {
private OnCommand onCommand;
private OffCommand offCommand;
private ChangeStationCommand changeStationCommand;
public OnCommand getOnCommand() {
return onCommand;
}
public void setOnCommand(OnCommand onCommand) {
this.onCommand = onCommand;
}
public OffCommand getOffCommand() {
return offCommand;
}
public void setOffCommand(OffCommand offCommand) {
this.offCommand = offCommand;
}
public ChangeStationCommand getChangeStationCommand() {
return changeStationCommand;
}
public void setChangeStationCommand(ChangeStationCommand changeStationCommand) {
this.changeStationCommand = changeStationCommand;
}
/**
* 开
*/
public void on() {
onCommand.excute();
}
/**
* 关
*/
public void off() {
offCommand.excute();
}
/**
* 换台
*/
public void changeStation() {
changeStationCommand.excute();
}
}
- 运行
public class Main {
public static void main(String[] args) {
// 创建接收者(物品)
TVReceiver tvReceiver = new TVReceiver();
// 创建指令(遥控器)
OnCommand onCommand = new OnCommand(tvReceiver);
OffCommand offCommand = new OffCommand(tvReceiver);
ChangeStationCommand changeStationCommand = new ChangeStationCommand(tvReceiver);
// 创建使用者
Invoker invoker = new Invoker();
invoker.setOffCommand(offCommand);
invoker.setOnCommand(onCommand);
invoker.setChangeStationCommand(changeStationCommand);
// 使用者作出指示
invoker.on();
System.out.println("------------");
invoker.changeStation();
System.out.println("------------");
invoker.off();
}
}
总结
优点
- 调用者对象与接受者对象没有任何依赖关系,降低了系统的耦合度
- 方便新的命令添加至系统中,扩展性强
缺点
- 过多的命令会导致系统中存在过多的具体命令类