命令模式即向一个invoker传入不同的命令,invoker将会根据传入的命令进行对应的操作
UML图:
Invoker类接收一个命令作为参数,其invoke方法调用了command的执行方法:
class Invoker {
private Command command;
public Invoker(Command command) {
this.command = command;
}
public void invoke() {
command.excute();
}
}
命令接口及其实现类:
interface Command {
void excute();
}
class ConcreteCommand1 implements Command {
private Receiver receiver;
public ConcreteCommand1(Receiver receiver) {
this.receiver = receiver;
}
@Override
public void excute() {
System.out.println("running concrete command 1");
receiver.setNumber(1);
}
}
接收器类,用于接收命令的处理结果:
class Receiver {
private int number = 0;
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}
客户端中调用:
Receiver receiver = new Receiver();
Invoker invoker1 = new Invoker(new ConcreteCommand1(receiver));
invoker1.invoke();
System.out.println(receiver.getNumber());
JAVA代码:https://github.com/zhuaizhuaixi/design-pattern/tree/master/src/designpattern/behavioral/command