【设计模式】策略模式与spring结合

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
简介: 在上一篇《【设计模式】策略模式》中,我们讲解了策略模式的基本概念和用法。策略模式是符合“开闭原则”的典型案例,但在上一篇文章中,我们发现,如果想调用其他的策略,虽然不用修改核心业务代码,但需要修改客户端代码。我们说,将策略的选择放在功能页面,当用户选择时,向后端传入策略,从数据库字典表中获取该策略对应的类的名字,再通过反射,获得对应的策略类。但如果不修改数据库,还有没有别的方法?当然有!

在上一篇《【设计模式】策略模式》中,我们讲解了策略模式的基本概念和用法。策略模式是符合“开闭原则”的典型案例,但在上一篇文章中,我们发现,如果想调用其他的策略,虽然不用修改核心业务代码,但需要修改客户端代码。我们说,将策略的选择放在功能页面,当用户选择时,向后端传入策略,从数据库字典表中获取该策略对应的类的名字,再通过反射,获得对应的策略类。但如果不修改数据库,还有没有别的方法?当然有!


使用spring注解!

我们将使用工厂+spring注解的方式实现!

1、工厂类

public class OrderIntegrateReadFactory {
    private final static Logger logger= LoggerFactory.getLogger(OrderIntegrateReadFactory.class);
    private Map<String,IVendeeContextStrategy> vendeeContextStrategyMap=new HashMap<String, IVendeeContextStrategy>();
    public Map<String, IVendeeContextStrategy> getVendeeContextStrategyMap() {
        return vendeeContextStrategyMap;
    }
    public void setVendeeContextStrategyMap(Map<String, IVendeeContextStrategy> vendeeContextStrategyMap) {
        this.vendeeContextStrategyMap = vendeeContextStrategyMap;
    }
    public boolean doAction(String strType, ReportDetail reportDetail, OrderDetail orderDetail){
        return this.vendeeContextStrategyMap.get(strType).getTicketContext(reportDetail,orderDetail);
    }
}


2、spring配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-3.2.xsd">
    <!--四种策略-->
    <bean id="orderIntegrateReadFactory" class="com.flight.inter.otaadapter.factory.OrderIntegrateReadFactory">
       <property name="vendeeContextStrategyMap">
           <map>
               <entry key="1" value-ref="ctripContextStrategy"/>
               <entry key="2" value-ref="qunarContextStrategy"/>
               <entry key="3" value-ref="aliquaContextStrategy"/>
               <entry key="4" value-ref="tongChengContextStrategy"/>
           </map>
       </property>
    </bean>
    <bean id="ctripContextStrategy" class="com.flight.inter.otaadapter.manage.cloudticket.CtripContextStrategy">
        <property name="huitiePiaoHao" ref="ctripHuiTieTicketNumber"/>
        <property name="redisManage" ref="policyRedis"/>
    </bean>
    <bean id="qunarContextStrategy" class="com.flight.inter.otaadapter.manage.cloudticket.QunarContextStrategy">
        <property name="huitiePiaoHao" ref="qunarHuiTieTicketNumber"/>
        <property name="redisManage" ref="policyRedis"/>
    </bean>
    <bean id="aliquaContextStrategy" class="com.flight.inter.otaadapter.manage.cloudticket.AliquaContextStrategy">
        <property name="huitiePiaoHao" ref="quaHuiTieTicketNumber"/>
        <property name="redisManage" ref="policyRedis"/>
    </bean>
    <bean id="tongChengContextStrategy" class="com.flight.inter.otaadapter.manage.cloudticket.TongChengContextStrategy">
        <property name="huitiePiaoHao" ref="TongChengHuiTieTicketNumber"/>
        <property name="redisManage" ref="policyRedis"/>
    </bean>
</beans>


3、接口类

public interface IVendeeContextStrategy {
    boolean getTicketContext(ReportDetail reportDetail, OrderDetail orderDetail);
}



4、具体实现类,以QunarContextStrategy策略为例

public class QunarContextStrategy implements IVendeeContextStrategy{
    private final static Logger logger= LoggerFactory.getLogger(QunarContextStrategy.class);
    HandleManage<TicketContext> huitiePiaoHao;
    RedisManager redisManage;
    public RedisManager getRedisManage() {
        return redisManage;
    }
    public void setRedisManage(RedisManager redisManage) {
        this.redisManage = redisManage;
    }
    public HandleManage<TicketContext> getHuitiePiaoHao() {
        return huitiePiaoHao;
    }
    public void setHuitiePiaoHao(HandleManage<TicketContext> huitiePiaoHao) {
        this.huitiePiaoHao = huitiePiaoHao;
    }
    @Override
    public boolean getTicketContext(ReportDetail reportDetail, OrderDetail orderDetail){
       try {
           TicketContext ticketContextQunar = QunarTicketContext(reportDetail, orderDetail);
           if (ticketContextQunar != null) {
               TicketContext ticketContext=huitiePiaoHao.handle(ticketContextQunar);
               if (ticketContext.isHuitieresult()){
                   redisManage.add("vendee-"+ticketContext.getTtsorderno(),"true");
                   redisManage.expire("vendee-"+ticketContext.getTtsorderno(),600);
                   logger.info("orderintegrate huitie success data {}",JSONObject.toJSONString(ticketContext));
                   return true;
               }
           }
       }catch (Exception e){
           logger.error("orerintegrate read ticketcontext error {}",e);
            return false;
       }
        return false;
    }
 }



5、模拟客户端调用

public class StrategyPatternDemo{
   public static void main(String[] args){
     OrderIntegrateReadFactory  orderIntegrateReadFactory = new  OrderIntegrateReadFactory ();
     String type = "1";
     ReportDetail reportDetail = new ReportDetail();
     OrderDetail orderDetail = new OrderDetail();
     reportDetail.setXXX();
     orderDetail.setXXX();
     ... ...
     Boolean boolean = orderIntegrateReadFactory.doAction(strType, reportDetail,orderDetail);
  }
}



 当需求中有新的类时,我们可以在只添加策略类,修改spring的配置文件来实现啦!

代码借鉴:

https://blog.csdn.net/zlts000/article/details/54754789










相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
2天前
|
设计模式 算法
设计模式之 Strategy(策略模式)
设计模式之 Strategy(策略模式)
23 1
|
2天前
|
设计模式 算法 PHP
php设计模式--策略模式(六)
php设计模式--策略模式(六)
11 0
|
2天前
|
设计模式 SQL Java
Spring中的设计模式
Spring中的设计模式
|
2天前
|
设计模式 算法 Java
小谈设计模式(3)—策略模式
小谈设计模式(3)—策略模式
|
2天前
|
设计模式 算法
【设计模式】阿里终面:你觉得这个例子是策略模式吗?
【设计模式】阿里终面:你觉得这个例子是策略模式吗?
9 1
|
2天前
|
设计模式 算法
大话设计模式(2)——策略模式
大话设计模式(2)——策略模式
7 1
|
2天前
|
设计模式 JavaScript 算法
js设计模式-策略模式与代理模式的应用
策略模式和代理模式是JavaScript常用设计模式。策略模式通过封装一系列算法,使它们可互换,让算法独立于客户端,提供灵活的选择。例如,定义不同计算策略并用Context类执行。代理模式则为对象提供代理以控制访问,常用于延迟加载或权限控制。如创建RealSubject和Proxy类,Proxy在调用RealSubject方法前可执行额外操作。这两种模式在复杂业务逻辑中发挥重要作用,根据需求选择合适模式解决问题。
|
2天前
|
设计模式 安全 Java
【初学者慎入】Spring源码中的16种设计模式实现
以上是威哥给大家整理了16种常见的设计模式在 Spring 源码中的运用,学习 Spring 源码成为了 Java 程序员的标配,你还知道Spring 中哪些源码中运用了设计模式,欢迎留言与威哥交流。
|
2天前
|
设计模式 算法 Java
Java 设计模式:探索策略模式的概念和实战应用
【4月更文挑战第27天】策略模式是一种行为设计模式,它允许在运行时选择算法的行为。在 Java 中,策略模式通过定义一系列的算法,并将每一个算法封装起来,并使它们可以互换,这样算法的变化不会影响到使用算法的客户。
23 1
|
2天前
|
设计模式 算法 Go
[设计模式 Go实现] 行为型~策略模式
[设计模式 Go实现] 行为型~策略模式