基于枚举实现策略设计模式

基于数据库实现策略模式

架构图

基于枚举实现策略设计模式_第1张图片

策略模式环境搭建

创建项目名称 springboot_ strategy
Maven依赖信息


    org.springframework.boot
    spring-boot-starter-parent
    2.0.1.RELEASE


    
    
        org.springframework.boot
        spring-boot-starter-web
    
    
        org.projectlombok
        lombok
        1.16.10
    
    
        commons-lang
        commons-lang
        2.6
    
    
        org.mybatis.spring.boot
        mybatis-spring-boot-starter
        1.1.1
    
    
    
        mysql
        mysql-connector-java
    

PayStrategy(抽象角色)

public interface PayStrategy {

    /**
     * 共同算法实现骨架
     * @return
     */
     public String toPayHtml();
}

ConcreteStrategy (具体实现角色)

@Component
public class AliPayStrategy  implements PayStrategy {
    public String toPayHtml() {
        return "调用支付宝支付接口";
    }
}


@Component
public class XiaoMiPayStrategy implements PayStrategy {
    public String toPayHtml() {
        return "调用小米支付接口";
    }
}

PayChannelEumn

 public enum PayChannelEumn {
    ALI_PAY("ali_pay"),
    XIAOMI_PAY("xiaomi_pay"),;
    private String payCode;

    PayChannelEumn(String payCode) {
        this.payCode = payCode;
    }

    public String getPayCode() {
        return this.payCode;
    }
}

ChannelHandler

 @Component
public class ChannelHandler {
    private static Map map = new ConcurrentHashMap<>();
    @Autowired
    private AliPayStrategy aliPayStrategy;
    @Autowired
    private XiaoMiPayStrategy xiaoMiPayStrategy;

    @PostConstruct
    public void init() {
        map.put(PayChannelEumn.ALI_PAY.getPayCode(), aliPayStrategy);
        map.put(PayChannelEumn.XIAOMI_PAY.getPayCode(), xiaoMiPayStrategy);
    }
    public PayStrategy getHandler(String payCode) {
        return map.get(payCode);
    }
}

PayContextServiceCopy (上下文)

  @RestController
public class PayContextServiceCopy {
    @Autowired
    private ChannelHandler channelHandler;

    @RequestMapping("/payHtml")
    public String toPayHtml(String payCode) {
        // 1.验证参数
        if (StringUtils.isEmpty(payCode)) {
            return "payCode不能为空!";
        }
        // 2.使用PayCode查询
        PayStrategy handler = channelHandler.getHandler(payCode);
        if (handler == null) {
            return "该渠道为空...";
        }
        return handler.toPayHtml();
    }

}

启动类

@SpringBootApplication(scanBasePackages = {"com.mayikt.designers"})
public class StrategyApp {
    public static void main(String[] args) {
        SpringApplication.run(StrategyApp.class, args);
    }
}

Yml

server:
  servlet:
    context-path: /
  port: 8088
spring:
  application:
    name: utils
  datasource:
    url: jdbc:mysql://localhost:3306/designers?characterEncoding=UTF-8
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver

测试

localhost:8088/payHtml?payCode=ali_pay

你可能感兴趣的:(设计模式系列)