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

命令模式

描述

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

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

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

基本使用

  • 定义抽象命令(所有命令都基于这个抽象命令定义)
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();
    }
}
相关推荐
端庄的战斗机1 天前
javascript 设计模式(文章很长,请自备瓜子,水果和眼药水)
开发语言·javascript·设计模式
饼干哥哥1 天前
我开发了一个「吃掉」别人Skill来升级的饕餮.Skill,现在免费开源
人工智能·设计模式·开源
CaffeinePro1 天前
什么是系统架构?架构师到底在做什么?
设计模式·架构
AI人工智能+电脑小能手1 天前
【大白话说Java面试题 第156题】【06_Spring篇】第16题:Spring 用到了哪些设计模式?
java·spring·设计模式·代理模式·工厂模式
前端百草阁1 天前
JavaScript 设计模式(23 种)
开发语言·前端·javascript·设计模式
geovindu1 天前
java: Singleton Pattern
java·开发语言·后端·单例模式·设计模式·创建型模式
geovindu2 天前
python: Functional Options Pattern
开发语言·后端·python·设计模式·惯用法模式·函数式选项模式
Kel2 天前
Pregel 为什么会成为LangGraph编排的心脏
人工智能·设计模式·架构
会周易的程序员2 天前
microLog 后端开发指南
开发语言·c++·物联网·设计模式·日志·iot·aiot
geovindu2 天前
go: Functional Options Pattern
开发语言·后端·设计模式·golang·函数式选项模式’·惯用法模式