Skip to content

Latest commit

 

History

History
77 lines (69 loc) · 1.81 KB

Command.md

File metadata and controls

77 lines (69 loc) · 1.81 KB

介绍

  • 属于行为型设计模式
  • 优点:降低耦合度,请求和接收者之间不存在引用,父类抽象算法,子类实现,更加灵活
  • 缺点:需要为不同的实现创建一个子类,使系统更加庞大
  • 命令模式应用在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