当前位置:首页 > 技术 > 正文内容

Spring 中常见的三种设计模式及其实现

访客 技术 2026年9月27日 12

1. 策略模式

策略模式在 Spring 中常用于根据上下文动态选择具体处理逻辑。其核心思想是定义一个统一接口,多个实现类各自负责一种策略。

以奖励发放系统为例,可定义如下接口:

public interface RewardDispatcher {
    boolean canHandle(RewardContext context);
    void dispatch(RewardContext context);
}

不同奖励类型(如积分、代金券、实物)分别实现该接口:

@Component
public class PointsDispatcher implements RewardDispatcher {
    @Override
    public boolean canHandle(RewardContext ctx) {
        return ctx.getRewardType() == RewardType.POINTS;
    }

    @Override
    public void dispatch(RewardContext ctx) {
        System.out.println("发放积分奖励");
    }
}

@Component
public class VoucherDispatcher implements RewardDispatcher {
    @Override
    public boolean canHandle(RewardContext ctx) {
        return ctx.getRewardType() == RewardType.VOUCHER;
    }

    @Override
    public void dispatch(RewardContext ctx) {
        System.out.println("发放代金券");
    }
}

关键点:

  • 使用 @Component 将实现类注册为 Spring Bean;
  • 通过 canHandle() 方法判断是否适用当前上下文;
  • 上下文对象(RewardContext)封装所有必要参数,便于扩展。

2. 工厂方法模式

工厂方法模式用于解耦对象创建与使用逻辑。在 Spring 中,可通过自动注入所有策略实现,并动态选择合适实例。

@Component
public class RewardDispatcherFactory {

    private final List<RewardDispatcher> dispatchers;

    public RewardDispatcherFactory(List<RewardDispatcher> dispatchers) {
        this.dispatchers = dispatchers;
    }

    public RewardDispatcher getDispatcher(RewardContext context) {
        return dispatchers.stream()
            .filter(d -> d.canHandle(context))
            .findFirst()
            .orElseThrow(() -> new IllegalArgumentException("No dispatcher found"));
    }
}

客户端调用示例:

@Service
public class RewardService {

    private final RewardDispatcherFactory factory;

    public RewardService(RewardDispatcherFactory factory) {
        this.factory = factory;
    }

    public void issueReward(RewardContext ctx) {
        RewardDispatcher dispatcher = factory.getDispatcher(ctx);
        dispatcher.dispatch(ctx);
    }
}

优势:新增奖励类型只需添加新实现类,无需修改工厂或服务逻辑,符合开闭原则。

3. Builder 模式

Builder 模式用于构建复杂对象,尤其适用于需要依赖注入参与构造过程的场景。与 Lombok 的简单 Builder 不同,Spring 管理的 Builder 可注入其他 Bean。

public class RewardContext {
    private final RewardType type;
    private final int quantity;
    private final String userId;

    private RewardContext(RewardType type, int quantity, String userId) {
        this.type = type;
        this.quantity = quantity;
        this.userId = userId;
    }

    @Component
    @Scope("prototype")
    public static class Builder {
        @Autowired
        private RewardRepository repository;

        private long rewardId;
        private String userId;

        public Builder rewardId(long id) {
            this.rewardId = id;
            return this;
        }

        public Builder forUser(String uid) {
            this.userId = uid;
            return this;
        }

        public RewardContext build() {
            RewardConfig config = repository.findById(rewardId);
            return new RewardContext(config.getType(), config.getAmount(), userId);
        }
    }

    // getters...
}

使用方式:

@Service
public class RewardOrchestrator {
    @Autowired
    private ApplicationContext ctx;

    public void process(long rewardId, String userId) {
        RewardContext context = ctx.getBean(RewardContext.Builder.class)
            .rewardId(rewardId)
            .forUser(userId)
            .build();

        // 后续分发逻辑...
    }
}

注意点:

  • Builder 类必须为 static,避免依赖外部实例;
  • 使用 @Scope("prototype") 确保每次获取新实例,避免状态污染;
  • 通过 ApplicationContext.getBean() 获取多例 Builder 实例。

相关文章

Linux crontab 详解

1) crontab 是什么cron 是 Linux 的定时任务守护进程;crontab 是用来编辑/查看“按时间周期执行命令”的表(cron table)。常见两类:用户 crontab:每个用户一份(crontab -e 编辑)系统级 crontab / cron.d:可指定执行用户(/etc/crontab、/etc/cron.d/*)2) crontab 时间...

Mac 安装 Node.js 指南

方法一:通过官网安装包(最简单,适合初学者)如果你只是想快速安装并开始使用,这是最直接的方法。访问 Node.js 官网。页面会显示两个版本:LTS (Recommended For Most Users):长期支持版,最稳定。建议选这个。Current:最新特性版,包含最新功能但可能不够稳定。下载 .pkg 安装包并运行。按照安装向导点击“下一步”即可完成。方法二:使用 Homebrew 安装(...

Dom\HTML_NO_DEFAULT_NS 的副作用:自动加闭合标签

在使用Dom\HTMLDocument时,Dom\HTML_NO_DEFAULT_NS 将禁止在解析过程中设置元素的命名空间, 此设置是为了与DOMDocument向后兼容而存在的。当使用它时,已知的一个副作用就是:自动加闭合标签例如 </img> 为什么会这样?当你使用:Dom\HTML_NO_DEFAULT_NS文档会变成 无命名空间模式,此时内部更接近 XML...

Laravel 事件和监听器创建

在 Laravel 中,使用 Artisan 命令创建 Events(事件) 和 Listeners(监听器) 是非常高效的。你可以通过以下几种方式来实现:1. 手动创建单个 Event如果你只想创建一个事件类,可以使用 make:event 命令:Bashphp artisan make:event UserRegistered执行后,文件将生成在 app/Even...

自定义域名解析神器 dnsmasq

什么是 dnsmasq?dnsmasq 是一个轻量级、功能强大的网络服务工具,专为小型和中等规模网络设计。它是一个综合的网络基础设施解决方案[1]。dnsmasq 能做什么?功能说明应用场景DNS 转发与缓存将 DNS 查询转发到上游服务器(ISP、Google DNS 等),并在本地缓存结果加快 DNS 查询速度,减少外部 DNS 流量本地 DNS解析本地网络设备的主机名,无需编辑&n...

linux screen 用法详情 (nohup 的替代方案)

一、screen 是什么?能干嘛?screen 是一个终端复用器,可以:在一个 SSH 会话中开多个“虚拟终端”SSH 断线后,程序仍然在后台运行随时重新连接到原来的会话特别适合:nohup 的替代方案跑脚本 / 爬虫 / 训练模型运维、远程开发二、安装 screen# CentOS / Rocky / Almayum install -y screen# Debian / Ubuntuapt i...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。