目录
什么是命令模式
命令模式是解除‘行为请求者’和'行为执行者'之间紧耦合的一种设计模式。将请求包裹成对象执行调用,被调用对象根据具体命令寻找具体执行者执行相应命令,并返回执行结果。
为什么要用命令模式
在很多情况下执行的请求和执行对象直接存在紧耦合关系,执行请求者必须深入执行者内部,从而在应对需求的变更时显得更加困难。命令模式解除双方的紧耦合,通过命令对象来实现双方的交互,从而在需求改变时,执行请求者和执行者之间能相互独立而不需要相互关系。在需求扩展方面,只需要针对新需求实现新命令即可。
命令模式组成
抽象命令
public abstract class Command {
protected final Receiver receiver;
public Command(Receiver receiver) {
this.receiver = receiver;
}
public abstract void execute();
}
具体命令
public class ConcreteCommand1 extends Command {
public ConcreteCommand1(){
super(new ConcreteReciver1());
}
public ConcreteCommand1(Receiver receiver) {
super(receiver);
}
@Override
public void execute() {
super.receiver.doSomething();
}
}
public class ConcreteCommand2 extends Command {
public ConcreteCommand2(){
super(new ConcreteReciver2());
}
public ConcreteCommand2(Receiver receiver) {
super(receiver);
}
@Override
public void execute() {
super.receiver.doSomething();
}
}
抽象接收者
public abstract class Receiver {
public abstract void doSomething();
}
具体接收者
public class ConcreteReciver1 extends Receiver {
@Override
public void doSomething() {
System.out.println("ConcreteReciver1 doSomething");
}
}
public class ConcreteReciver2 extends Receiver {
@Override
public void doSomething() {
System.out.println("ConcreteReciver2 doSomething");
}
}
调用者
public class Invoker {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void action() {
this.command.execute();
}
}
测试驱动
public class Client {
public static void main(String[] args) {
Invoker invoker = new Invoker();
Command command = new ConcreteCommand1();
invoker.setCommand(command);
invoker.action();
}
}