- 属于行为型设计模式
- 优点:降低耦合度,请求和接收者之间不存在引用,父类抽象算法,子类实现,更加灵活
- 缺点:需要为不同的实现创建一个子类,使系统更加庞大
- 命令模式应用在Tomcat中,HttpConnector发出请求,HttpProcessor作为命令,Container为抽象接收者
public interface Command {
public void exec();
}
public class CommandImpl implements Command {
private Receiver receiver;
public CommandImpl(Receiver receiver) {
this.receiver = receiver;
}
@Override
public void exec() {
receiver.action();
}
}
public class Receiver {
public String name;
public Receiver(String name) {
this.name = name;
}
public void action() {
System.out.println(name + " receive command");
}
}
public class Invoker {
private Command command;
public Invoker(Command command) {
this.command = command;
}
public void action() {
command.exec();
}
}
public class Main {
public static void main(String[] args) {
Receiver receiver = new Receiver("stalary");
Command command = new CommandImpl(receiver);
Invoker invoker = new Invoker(command);
invoker.action();
}
}
// 测试结果
stalary receive command