设计模式简述(九)命令模式

命令模式

描述

命令模式是一种体现高内聚的行为模式。

将整个请求封装成一个命令对象 ,由这个命令对象完成所需业务调用。

命令对象封装了该命令需要的所有逻辑,不需要调用方关注内部细节。

基本使用

  • 定义抽象命令(所有命令都基于这个抽象命令定义)
java 复制代码
public abstract class AbstractCommand {
    abstract void execute();
}
  • 定义命令对象内要实际调用的业务对象
java 复制代码
public interface IReceiver {
    void action();
}

public class ReceiverA implements IReceiver {
    @Override
    public void action() {
        System.out.println("ReceiverA action ....");
    }
}

public class ReceiverB implements IReceiver {
    @Override
    public void action() {
        System.out.println("ReceiverB action ....");
    }
}
  • 定义两个具体的命令
java 复制代码
public class CommandA extends AbstractCommand{
    private IReceiver receiver;

    public CommandA(IReceiver receiver) {
        this.receiver = receiver;
    }

    @Override
    void execute() {
        System.out.println("commandA....");
        receiver.action();
    }
}

public class CommandAB extends AbstractCommand{
    private IReceiver[] receivers;

    public CommandAB(IReceiver... receivers) {
        this.receivers = receivers;
    }

    @Override
    void execute() {
        System.out.println("commandA....");
        for (IReceiver receiver : receivers) {
            receiver.action();
        }
    }
}

使用

java 复制代码
public class Sample {
    public static void main(String[] args) {
        IReceiver receiverA = new ReceiverA();
        IReceiver receiverB = new ReceiverB();
        AbstractCommand command = new CommandA(receiverA);
        command.execute();
        AbstractCommand commandAb = new CommandAB(receiverA, receiverB);
        commandAb.execute();
    }
}
相关推荐
wu~9705 小时前
手撕四种常用设计模式(工厂,策略,代理,单例)
java·单例模式·设计模式·代理模式·抽象工厂模式·策略模式
敲代码的 蜡笔小新11 小时前
【行为型之访问者模式】游戏开发实战——Unity灵活数据操作与跨系统交互的架构秘诀
unity·设计模式·c#·访问者模式
软考真题app1 天前
软件设计师考试结构型设计模式考点全解析
设计模式·软件设计师·结构型设计模式·考试考点
xiaolin03331 天前
【设计模式】- 行为型模式1
设计模式·状态模式·责任链模式·策略模式·命令模式·模板方法模式·行为型模式
沐土Arvin1 天前
深入理解 requestIdleCallback:浏览器空闲时段的性能优化利器
开发语言·前端·javascript·设计模式·html
bao_lanlan1 天前
兰亭妙微:用系统化思维重构智能座舱 UI 体验
ui·设计模式·信息可视化·人机交互·交互·ux·外观模式
总是难免1 天前
设计模式 - 单例模式 - Tips
java·单例模式·设计模式
Java致死2 天前
设计模式Java
java·开发语言·设计模式
ghost1432 天前
C#学习第23天:面向对象设计模式
开发语言·学习·设计模式·c#
敲代码的 蜡笔小新2 天前
【行为型之迭代器模式】游戏开发实战——Unity高效集合遍历与场景管理的架构精髓
unity·设计模式·c#·迭代器模式