命令模式(Command)

命令模式

一. 命令模式

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

END

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值