java设计模式--策略(3)

前景 集成spring容器管理 + 数据库 去除多重if else

  • 注意事项
    • 项目中存在架构包, 如异常拦截等等
    • 策略集成spring容器,需要给类加上@Compent注解

项目演示地址

查看调用

 @PostMapping(value = "/strategy/normal/pay")
    public BaseResource pay(@RequestParam String code) {

        if(StringUtils.isEmpty(code)) {

            throw new ViewParamException();
        }

        /**
         * 从数据库获取beanId
         */
        PaymentChannel paymentChannel = paymentChannelMapper.getPaymentChannel(code);

        if(null == paymentChannel) {

            throw new DataException();
        }

        String strategyBeanId = paymentChannel.getStrategyBeanId();
        if(StringUtils.isEmpty(strategyBeanId)) {

            throw new DataException("beanId不存在");
        }

        /**
         * 使用spring容器通过的工具从容器中获取bean
         */
        Pay pay = SpringUtils.getBean(strategyBeanId, Pay.class);

        String call = pay.call();

        return BaseResource.fromSuccess(call);

    }

在这里插入图片描述

  • 上代码

定义接口

public interface Pay {

    String call();
}
@Component
public class AliPay implements Pay {


    @Override
    public String call() {
        System.out.println("调用支付宝");
        return "ali";
    }
}
@Component
public class UnionPay implements Pay {

    @Override
    public String call() {
        System.out.println("调用银联");
        return "union";
    }
}
@Component
public class WxPay implements Pay {

    @Override
    public String call() {
        System.out.println("调用微信");
        return "wx";
    }
}

dao 层

public interface PaymentChannelMapper {

    @Select("SELECT  id ,channelName ,channelId,strategyBeanId " +
            "FROM payment_channel where channelId=#{payCode}")
    PaymentChannel getPaymentChannel(String payCode);
}

@Data
public class PaymentChannel {

    private Integer id;
    /** 渠道名称 */
    private String channelName;
    /** 渠道ID */
    private String channelId;
    /**
     * 策略执行beanId
     */
    private String strategyBeanId;
}

yml 配置

###服务启动端口号
server:
  port: 8080
spring:
  ###数据库相关连接
  datasource:
    username: root
    password: 17730088312@163.com
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:33061/design_pattern?useUnicode=true&characterEncoding=UTF-8&useSSL=false

项目演示地址

表结构

drop database if exists `design_pattern`;
create database `design_pattern` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;

CREATE TABLE IF NOT EXISTS `payment_channel`(
   `id` INT UNSIGNED AUTO_INCREMENT,
   `channelName` VARCHAR(100) NOT NULL,
   `channelId` VARCHAR(40) NOT NULL,
   `strategyBeanId` VARCHAR(40) NOT NULL,
   PRIMARY KEY ( `id` )
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

项目演示地址

发布了42 篇原创文章 · 获赞 19 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_37828719/article/details/103800353