设计模式之命令模式

命令模式

  1. 命令模式结构图:

  2. 示例代码:

    // 命令接受者,负责具体执行命令
    public class Receiver {
    
        public void action(){
            System.out.println("开始执行命令========");
        }
    }
    
    // 命令抽象类
    public interface Command {
        void execute();
    }
    
    // 具体命令角色A
    public class ConcreteCommandA implements Command{
    
        private Receiver receiver;
    
        public ConcreteCommandA(Receiver receiver) {
            this.receiver = receiver;
        }
    
        @Override
        public void execute() {
            System.out.println("执行命令A");
            receiver.action();
        }
    }
    
    // 具体命令角色B
    public class ConcreteCommandB implements Command{
    
        private Receiver receiver;
    
        public ConcreteCommandB(Receiver receiver) {
            this.receiver = receiver;
        }
    
        @Override
        public void execute() {
            System.out.println("执行命令B");
            receiver.action();
        }
    }
    
    // 命令请求者
    public class Invoker {
        List<Command> list = new ArrayList<>();
    
        public void attach(Command command){
            System.out.println("添加命令");
            list.add(command);
        }
    
        public void detach(){
         System.out.println("撤销命令");
         if (!list.isEmpty()){
             list.remove(list.size() -1);
         }
       }
    
        public void execute(){
            list.forEach(a -> a.execute());
        }
    }
    
    // 测试类
    public class CommandTest {
    
        public static void main(String[] args) {
            Invoker invoker = new Invoker();
            invoker.attach(new ConcreteCommandA(new Receiver()));
            invoker.attach(new ConcreteCommandA(new Receiver()));
            invoker.attach(new ConcreteCommandB(new Receiver()));
            invoker.attach(new ConcreteCommandB(new Receiver()));
            invoker.execute();
        }
    }
    
    
  3. 总结:

    优点:通过引入抽象接口,解偶了命令请求与实现,扩展性好,支持组合命令,可在现有命令的基础上,增加额外的功能;

    缺点:具体命令类可能过多,增加了系统的复杂性.

posted @ 2021-04-25 07:37  justKen  阅读(39)  评论(0编辑  收藏  举报