Spring与设计模式实战之策略模式

news2024/9/20 16:37:58

Spring与设计模式实战之策略模式

引言

在现代软件开发中,设计模式是解决常见设计问题的有效工具。它们提供了经过验证的解决方案,帮助开发人员构建灵活、可扩展和可维护的系统。本文将探讨策略模式在Spring框架中的应用,并通过实际例子展示如何通过Spring的特性来实现和管理策略模式。

1. 策略模式(Strategy Pattern)的概述

策略模式是一种行为型设计模式,它允许定义一系列算法,并将每个算法封装起来,使它们可以互换。这种模式让算法的变化独立于使用算法的客户。在Java中,策略模式通常通过接口和它们的实现类来实现。

1.1 策略模式的结构

  • 策略接口:声明了所有具体策略类都必须实现的操作。
  • 具体策略类:实现了策略接口,定义了具体的算法。
  • 上下文类:维护一个对策略对象的引用,并在需要时调用策略对象的方法。

2. ApplicationContextAware接口的介绍

在Spring框架中,ApplicationContext是一个非常核心的概念。它代表Spring IoC容器,负责实例化、配置和管理Beans。通过实现ApplicationContextAware接口,Spring Bean可以访问Spring的ApplicationContext,从而获取其他Beans或上下文信息。

2.1 ApplicationContextAware的使用

当一个Bean实现ApplicationContextAware接口时,Spring会在初始化该Bean时自动调用其setApplicationContext方法,并传入ApplicationContext实例。这样,该Bean就可以使用这个上下文来获取其他Beans或与Spring容器交互。

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class MyBean implements ApplicationContextAware {
    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public void doSomething() {
        // 使用applicationContext获取其他Bean
        AnotherBean anotherBean = applicationContext.getBean(AnotherBean.class);
        anotherBean.performTask();
    }
}

3. StrategyFactory的设计与实现

StrategyFactory是一个策略工厂类,负责根据业务需求创建和提供策略实例。它使用自定义的@TradeStrategy注解来识别和创建具体的策略类实例。

3.1 自定义注解@TradeStrategy

我们首先定义一个自定义注解@TradeStrategy,用于标注具体的策略类。这个注解可以在运行时通过反射机制进行处理。

import java.lang.annotation.*;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TradeStrategy {
    String value();
}

3.2 StrategyFactory的实现

StrategyFactory使用Spring的ApplicationContext来动态地获取所有添加了@TradeStrategy注解的Beans,并根据业务编码获取具体的策略类实例。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

@Component
public class StrategyFactory {

    @Autowired
    private ApplicationContext applicationContext;

    private Map<String, ITradeStrategy> strategyMap = new HashMap<>();

    @PostConstruct
    public void init() {
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(TradeStrategy.class);
        for (Object bean : beansWithAnnotation.values()) {
            TradeStrategy tradeStrategy = bean.getClass().getAnnotation(TradeStrategy.class);
            strategyMap.put(tradeStrategy.value(), (ITradeStrategy) bean);
        }
    }

    public ITradeStrategy getStrategy(String code) {
        return strategyMap.get(code);
    }
}

4. TradeStrategyContext的角色

TradeStrategyContext充当策略上下文的角色,提供获取策略实例的方法。它包含一个tradeStrategyMap,用于存储策略枚举和对应的策略实现。

4.1 TradeStrategyContext的实现

TradeStrategyContext依赖于StrategyFactory来获取策略实例,并提供一个统一的方法来执行策略。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class TradeStrategyContext {

    @Autowired
    private StrategyFactory strategyFactory;

    public void executeStrategy(String code) {
        ITradeStrategy strategy = strategyFactory.getStrategy(code);
        if (strategy != null) {
            strategy.process();
        } else {
            throw new IllegalArgumentException("No strategy found for code: " + code);
        }
    }
}

5. ITradeStrategy接口及其实现

ITradeStrategy是一个策略接口,声明了一个process方法,所有具体策略类都需要实现这个接口。

5.1 ITradeStrategy接口

public interface ITradeStrategy {
    void process();
}

5.2 具体策略类的实现

以下是几个具体策略类的实现示例:

import org.springframework.stereotype.Component;

@TradeStrategy("apply")
@Component
public class ApplyServiceStrategy implements ITradeStrategy {
    @Override
    public void process() {
        System.out.println("Processing apply service strategy");
    }
}

@TradeStrategy("redeem")
@Component
public class RedeemServiceStrategy implements ITradeStrategy {
    @Override
    public void process() {
        System.out.println("Processing redeem service strategy");
    }
}

@TradeStrategy("convert")
@Component
public class CovertServiceStrategy implements ITradeStrategy {
    @Override
    public void process() {
        System.out.println("Processing convert service strategy");
    }
}

@TradeStrategy("withdraw")
@Component
public class WithDrawServiceStrategy implements ITradeStrategy {
    @Override
    public void process() {
        System.out.println("Processing withdraw service strategy");
    }
}

6. TradeController的设计

TradeController是交易请求的统一入口,提供了一个tradeIndex方法来处理交易请求。它使用TradeStrategyContext来获取并执行相应的策略。

6.1 TradeController的实现

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TradeController {

    @Autowired
    private TradeStrategyContext tradeStrategyContext;

    @GetMapping("/trade")
    public String tradeIndex(@RequestParam String code) {
        tradeStrategyContext.executeStrategy(code);
        return "Trade executed successfully for strategy: " + code;
    }
}

7. 策略的动态加载与维护

通过Spring的ApplicationContextStrategyFactory可以动态地获取所有添加了@TradeStrategy注解的Beans,并根据业务编码获取具体的策略类实例。这使得系统在添加新的策略时,只需要添加新的策略类并标注@TradeStrategy注解即可,无需修改现有代码。

8. 策略的扩展性

通过自定义注解和策略工厂,系统可以很容易地添加新的策略,而不需要修改现有的代码,提高了系统的扩展性。例如,当需要添加一个新的交易策略时,只需要创建一个新的策略类并标注@TradeStrategy注解,然后在需要时通过业务编码来调用该策略。

8.1 添加新策略的示例

@TradeStrategy("newStrategy")
@Component
public class NewServiceStrategy implements ITradeStrategy {
    @Override
    public void process() {
        System.out.println("Processing new service strategy");
    }
}

总结

策略模式在Spring框架中的应用展示了设计模式的强大和灵活性。通过自定义注解和Spring的ApplicationContext,我们可以实现策略的动态管理和扩展。这种方法不仅提高了代码的可维护性,还增强了系统的可扩展性。在实际项目中,合理地应用设计模式和Spring特性,可以显著提升系统的设计质量和开发效率。

附一张基金代销渠道订单处理流程图
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1930955.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

three.js领衔,10大基于webGL的JavaScript库。

Three.js的赫赫威名补多少&#xff0c;不了解的自行搜索或者翻看大宇之前的文章&#xff0c;除了three.js外&#xff0c;我想实现web3D效果还有其他库吗&#xff1f;答案是有的&#xff0c;而且还不少。 除了 Three.js&#xff0c;还有一些基于 WebGL 的库和框架&#xff0c;它…

动态环境下的激光slam论文列表

文章目录 Scan Context: Egocentric Spatial Descriptor for Place Recognition within 3D Point Cloud Map&#xff08;2018&#xff09;LIO-CSI: LiDAR inertial odometry with loop closure combined with semantic information&#xff08;2021&#xff09;Semantic Lidar-…

防火墙--双机热备

目录 双击热备作用 防火墙和路由器备份不同之处 如何连线 双机 热备 冷备 VRRP VGMP&#xff08;华为私有协议&#xff09; 场景解释 VGMP作用过程 主备的形成场景 接口故障的切换场景 整机故障 原主设备故障恢复的场景 如果没有开启抢占 如果开启了抢占 负载分…

网络原理(上)

前言&#x1f440;~ 上一章我们介绍了网络的一些基础知识&#xff0c;今天来讲解一下网络原理相关的知识点&#xff0c;分三篇进行阐述内容有点多​​​​​​​ 再谈协议分层 应用层 传输层&#xff08;重点&#xff09; UDP协议 TCP协议 TCP如何完成可靠传输&#xff…

在 PostgreSQL 里如何处理数据的归档和清理过程中的数据完整性验证?

&#x1f345;关注博主&#x1f397;️ 带你畅游技术世界&#xff0c;不错过每一次成长机会&#xff01;&#x1f4da;领书&#xff1a;PostgreSQL 入门到精通.pdf 文章目录 在 PostgreSQL 里如何处理数据的归档和清理过程中的数据完整性验证 在 PostgreSQL 里如何处理数据的归…

3D数字孪生项目运行卡顿,来看看它要求的电脑配置。

有些小伙伴和我说&#xff0c;数字孪生项目运行卡顿&#xff0c;不知道啥原因&#xff0c;根源还是这类项目是浏览器渲染&#xff0c;对电脑配置要求很高。 运行3D数字孪生项目需要一台性能强大的电脑&#xff0c; 以下是一个推荐的配置清单&#xff1a; 1. 处理器&#xff1…

css实现每个小盒子占32%,超出就换行

代码 <div class"visitors"><visitor class"item" v-for"(user,index) in userArr" :key"user.id" :user"user" :index"index"></visitor></div><style lang"scss" scoped&…

Porfinet转DeviceNet主总线协议转换网关

产品功能 1. 远创智控YC-DNTM-PN型网关是Porfinet从转Devicenet主工业级Porfinet网关。‌这种网关设备允许将Porfinet网络中的设备连接到Devicenet网络中&#xff0c;‌从而实现不同工业通信协议之间的互操作性。‌这些网关设备通常具有两个以太网接口&#xff0c;‌分别用于连…

shell脚本-linux如何在脚本中远程到一台linux机器并执行命令

需求&#xff1a;我们需要从11.0.1.17远程到11.0.1.16上执行命令 实现&#xff1a; 1.让11.0.1.17 可以免密登录到11.0.1.16 [rootlocalhost ~]# ssh-keygen Generating public/private rsa key pair. Enter file in which to save the key (/root/.ssh/id_rsa): Created d…

Ubuntu 22.04.4 LTS (linux) 安装iftop 监控网卡流量 软件

1 安装iftop sudo apt update sudo apt-get install iftop 2 监控网卡 sudo iftop -i eth0 -n -p 界面最上面&#xff0c;显示的是类似刻度尺的刻度范围&#xff0c;显示流量图形的长条作标尺用的。 中间的< >这两个左右箭头&#xff0c;表示的是流量的进出方向.TX&…

使用JS和CSS制作的小案例(day二)

一、写在开头 本项目是从github上摘取&#xff0c;自己练习使用后分享&#xff0c;方便登录github的小伙伴可以看本篇文章 50项目50天​编辑https://github.com/bradtraversy/50projects50dayshttps://github.com/bradtraversy/50projects50days有兴趣的小伙伴可以自己去gith…

美式键盘 QWERTY 布局的起源

注&#xff1a;机翻&#xff0c;未校对。 The QWERTY Keyboard Is Tech’s Biggest Unsolved Mystery QWERTY 键盘是科技界最大的未解之谜 It’s on your computer keyboard and your smartphone screen: QWERTY, the first six letters of the top row of the standard keybo…

Redis的热key解决

1、Redis热Key会带来哪些问题 1、流量集中&#xff0c;达到物理网卡上限。 当某一热点 Key 的请求在某一主机上超过该主机网卡上限时&#xff0c;由于流量的过度集中&#xff0c;会导致服务器中其它服务无法进行。 2、请求过多&#xff0c;缓存分片服务被打垮。 如果热点过于…

Linux入门笔记(指令)

操作系统是什么&#xff1f; 操作系统是一款做软硬件管理的软件。计算机系统自下而上可以大致分为4部分&#xff1a;硬件、操作系统、应用程序和用户。操作系统管理各种计算机硬件&#xff0c;为应用程序提供基础&#xff0c;并且充当计算机硬件与用户之间的中介。重点&#x…

泛微e-cology WorkflowServiceXml SQL注入漏洞(POC)

漏洞描述&#xff1a; 泛微 e-cology 是泛微公司开发的协同管理应用平台。泛微 e-cology v10.64.1的/services/接口默认对内网暴露&#xff0c;用于服务调用&#xff0c;未经身份认证的攻击者可向 /services/WorkflowServiceXml 接口发送恶意的SOAP请求进行SQL注入&#xff0c;…

高并发项目(一):内存池的概念/定长内存池的实现

目录 一、池化技术及其优势 1.1什么是池化技术 1.2内存池的作用 1.3malloc的原理 二、定长内存池的实现 一、池化技术及其优势 1.1什么是池化技术 所谓 “ 池化技术 ” &#xff0c;就是程序先向系统申请过量的资源&#xff0c;然后自己管理&#xff0c;以备不时之需。之所…

微调 Florence-2 - 微软的尖端视觉语言模型

Florence-2 是微软于 2024 年 6 月发布的一个基础视觉语言模型。该模型极具吸引力&#xff0c;因为它尺寸很小 (0.2B 及 0.7B) 且在各种计算机视觉和视觉语言任务上表现出色。 Florence 开箱即用支持多种类型的任务&#xff0c;包括: 看图说话、目标检测、OCR 等等。虽然覆盖面…

吴恩达大模型系列课程《Prompt Compression and Query Optimization》中文学习打开方式

Prompt Compression and Query Optimization GPT-4o详细中文注释的Colab观看视频1 浏览器下载插件2 打开官方视频 GPT-4o详细中文注释的Colab 中文注释链接&#xff1a;https://github.com/Czi24/Awesome-MLLM-LLM-Colab/tree/master/Courses/Prompt-Compression-and-Query-Op…

Activity工作流框架——生成数据表

自动生成activiti数据库表 首先第一步&#xff0c;引入activiti依赖 <dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency>&…

生成树(STP)协议

一、生成树的技术背景 1、交换机单线路上链,存在单点故障,上行线路及设备都不具备冗余性,一旦链路或上行设备发生故障,网络将面临断网。 总结:以下网络不够健壮,不具备冗余性。 2、因此引入如下网络拓扑结构: 上述冗余拓扑能够解决单点故障问题,但同时冗拓扑也带来了…