命令模式(Command)

命令模式git

一. 命令模式

1.1 定義

  • 對於「行爲請求者」和「行爲實現者」,將一組行爲抽象爲對象,實現兩者的鬆耦合.

1.2 角色

  • Command:抽象命令接口.
  • ConcreteCommand:具體命令.
  • Receiver:最終執行命令的對象.
  • Invoker:命令對象的入口.

二. 具體實現

1.1 建立Command接口

public interface ICommand {
        void execute();
    }

1.2 建立命令執行對象

public class Receiver {
        public void execute(){
            System.out.println("receiver execute ... ");
        }
    }

1.3 建立具體Command實現類

public class ConcreteCommandA implements ICommand {
        private Receiver receiver;
        public ConcreteCommandA(Receiver receiver){
            this.receiver = receiver;
        }
        @Override
        public void execute() {
            System.out.println("ConcreteCommandA execute ...");
            receiver.execute();
        }
    }
    public class ConcreteCommandB implements ICommand {
        private Receiver receiver;
        public ConcreteCommandB(Receiver receiver){
            this.receiver = receiver;
        }
        @Override
        public void execute() {
            System.out.println("ConcreteCommandB execute ...");
            receiver.execute();
        }
    }

1.4 建立命令入口

public class Invoker {
        private ICommand concreteCommandA, concreteCommandB;
        public Invoker(ICommand concreteCommandA, ICommand concreteCommandB){
            this.concreteCommandA = concreteCommandA;
            this.concreteCommandB = concreteCommandB;
        }
        public void orderA(){
            concreteCommandA.execute();
        }
        public void orderB(){
            concreteCommandB.execute();
        }
    }

1.5 調用

public static void main(String[] args) {
        Receiver receiver = new Receiver();
        Invoker invoker = new Invoker(new ConcreteCommandA(receiver), new ConcreteCommandB(receiver));
        invoker.orderA();
        invoker.orderB();
    }

1.6 輸出

ConcreteCommandA execute ...
    receiver execute ... 
    ConcreteCommandB execute ...
    receiver execute ...

三. 優缺點

3.1 優勢

  • 下降耦合度.
  • 新增一個命令/一組命令簡單.
  • 調用同一方法實現不一樣功能.

3.2 缺點

  • 會產生過多具體命令類.

四. 源碼

https://github.com/Seasons20/DisignPattern.git

ENDgithub

相關文章
相關標籤/搜索