注解实现策略模式

发布时间:2024年01月25日

代码结构如下

代码结构

代码如下

@Getter
@AllArgsConstructor
public enum AuditPlutusEnum {

    BACK("回款"),

    REFUND("退款"),

    INVOICE("开票");

    private final String name;
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Component
public @interface AuditStrategyType {

    @AliasFor(annotation = Component.class)
    String value() default "";

    AuditPlutusEnum type();


}
 */
@Configuration
public class AuditStrategyConfig {

    @Bean
    public AuditStrategyRunner auditStrategyRunner(List<AuditPlutusStrategy> strategies) {
        Map<AuditPlutusEnum, AuditPlutusStrategy> strategyMap = strategies.stream()
                .collect(Collectors.toMap(
                        // 获取策略标识
                        s -> s.getClass().getAnnotation(AuditStrategyType.class).type(),
                        s -> s
                ));
        return (flag, auditPlutusRo) -> strategyMap.get(flag).audit(auditPlutusRo);
    }
}
public interface AuditStrategyRunner {


    void audit(AuditPlutusEnum type, AuditPlutusRo auditPlutusRo);
}
public interface AuditPlutusStrategy {


    void audit(AuditPlutusRo ro);
}
@AuditStrategyType(type = AuditPlutusEnum.REFUND)
public class AuditRefundStrategy implements AuditPlutusStrategy {

    @Override
    public void audit(AuditPlutusRo ro) {
        // todo: 2024/1/24  退款相关处理
    }
}```

```java
@AuditStrategyType(type = AuditPlutusEnum.INVOICE)
public class AuditInvoiceStrategy implements AuditPlutusStrategy {

    @Override
    public void audit(AuditPlutusRo ro) {
        // todo: 2024/1/24  开票相关处理
    }
}
@AuditStrategyType(type = AuditPlutusEnum.BACK)
public class AuditBackStrategy implements AuditPlutusStrategy {

    @Override
    public void audit(AuditPlutusRo ro) {
        // todo: 2024/1/24  回款相关处理
    }
}

调用


    @Autowired
    private AuditStrategyRunner auditStrategyRunner;

    public ResultData<?> auditBack(AuditPlutusRo ro) {
        log.info("【{}】审核-业财回调处理,审核编号为:{},传入参数为:{}", ro.getAuditPlutusEnum().getName(), ro.getAuditNo(), JSON.toJSONString(ro));
        auditStrategyRunner.audit(ro.getAuditPlutusEnum(), ro);
        return ResultData.SUCCESS;
    }
文章来源:https://blog.csdn.net/qq_17589751/article/details/135828263
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。