命令模式:将请求封装成一个命令,使用命令对象将请求的调用者和接收者进行分离,从而降低耦合性
优点:类间解耦,具有良好的扩展性
标准类图:
抽象接收者:
public interface Receiver {
void doSomething();
}
具体接受者:
public class ConcreteReceiver implements Receiver {
@Override
public void doSomething() {
System.out.println("do some thing");
}
public void concreteDoSomething(){
System.out.println("concrete do some thing");
}
}
抽象命令:
public interface Command {
void execute();
}
具体命令:
public class ConcreteCommand implements Command {
private Receiver receiver = new ConcreteReceiver();
public ConcreteCommand() {
}
public ConcreteCommand(Receiver receiver) {
this.receiver = receiver;
}
@Override
public void execute() {
receiver.doSomething();
}
}
调用者:
public class Invoker {
private Command command;
public Invoker(Command command) {
super();
this.command = command;
}
public Invoker(){}
public void invoke(){
this.command.execute();
}
}
场景类:
public class Client {
public static void main(String[] args) {
Command command = new ConcreteCommand();
Invoker invoker = new Invoker(command);
invoker.invoke();
}
}
修改命令后不会引起高层调用者的变化,只需要传递变动过后的命令即可