目录
1.简介
将一个请求封装成一个对象,从而可以使用不同的请求把客户端参数化,对于请求排队或者记录请求日志,可以提供撤销和恢复功能。其中大概会有以下几个角色,Receive,Command,Invoker。其中Reveiver可以有多个,每个Reveiver都有自己业务需要处理;Command为整个命令模式的核心,其中涉及到对那个Receiver的命令处理,也可以有多个;Invoker就是调用者,接收命令,执行命令。
2.优点
实现类间解耦,Reveiver和Invoker之间没有任何依赖关系,Comand的子类具有高扩展性,可结合责任链实现命令族解析,结合模板减少Command子类膨胀的问题。
3.缺点
当Commond子类过多,会造成类膨胀的问题。
4.形式
抽象Receiver
public abstract class AReceiver {
public abstract void method();
}
具体Receiver1
public class Receiver1 extends AReceiver {
public void method() {
System.out.println("Receiver1的业务处理");
}
}
具体Receiver2
public class Receiver2 extends AReceiver {
public void method() {
System.out.println("Receiver2的业务处理");
}
}
抽象Command
public abstract class ACommand {
public abstract void execute();
}
具体Command1
public class Command1 extends ACommand {
private AReceiver receiver;
public Command1(AReceiver _receiver) {
this.receiver = _receiver;
}
public void execute() {
System.out.println("调用receiver处理业务");
this.receiver.method();
}
}
具体Command2
public class Command2 extends ACommand {
private AReceiver receiver;
public Command2(AReceiver _receiver) {
this.receiver = _receiver;
}
public void execute() {
System.out.println("调用receiver处理业务");
this.receiver.method();
}
}
Invoker调用者
public class Invoker {
private ACommand command;
public void setCommand(ACommand command) {
System.out.println("设置需要执行的命令");
this.command = _command;
}
public void action() {
System.out.println("执行命令");
this.command.execute();
}
}
测试类
public class Test {
public static void main(String[] args) {
Invoker invoker = new Invoker();
AReceiver receiver = new Receiver1();
ACommand command = new Command1(receiver);
invoker.setCommand(command);
invoker.action();
}
}
5.扩展
下错了命令,想反悔怎么办?没有月关宝盒,没有穿越,没有后悔药,只好回滚了,我滚...
抽象Receiver
public abstract class AReceiver {
public abstract void method();
public void rollBack() {
System.out.println("菠萝菠萝蜜");
}
}