`
richand730
  • 浏览: 3127 次
社区版块
存档分类
最新评论

策略模式+注解去除多余if else

    博客分类:
  • java
 
阅读更多

1. 创建自定义注解 TaxTypeAnnotation

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

 

2. 创建策略类 TaxStrategy

定义对应策略的类型常量

public interface TaxStrategy {
    String OUTER_TAX_STRATEGY = "outer";
    String INNER_TAX_STRATEGY = "inner";
    double calc(long amount);
}

 定义对应实现类

@TaxTypeAnnotation(taxType = OUTER_TAX_STRATEGY)
public class OuterTaxStrategy implements TaxStrategy{

    @Override
    public double calc(long amount) {
        final double taxRate = 0.2;
        return amount / (1 + taxRate) * taxRate;
    }
}

 

@TaxTypeAnnotation(taxType = INNER_TAX_STRATEGY)
public class InnerTaxStrategy implements TaxStrategy{

    @Override
    public double calc(long amount) {
        final double taxRate = 0.2;
        return amount * taxRate;
    }
}

 

3. 创建工厂类

public class AnnotationTaxStrategyFactory {
    static Map<String,TaxStrategy> taxStrategyMap = new HashMap<>(8);
    static {
        registerTaxStrategy();
    }

    /**
     *  通过map获取税策略,当增加新的税策略时无需修改代码,对修改封闭,对扩展开放,遵循开闭原则
     * @param taxType
     */
    public static TaxStrategy getTaxStrategy(String taxType) throws Exception {
        // 当增加新的税类型时,需要修改代码,同时增加圈复杂度
        if (taxStrategyMap.containsKey(taxType)) {
            return taxStrategyMap.get(taxType);
        } else {
            throw new Exception("The tax type is not supported.");
        }
    }

    private static void registerTaxStrategy(){
        //找寻包目录下所有带有TaxTypeAnnotation注解的类
        Set<Class<?>> classSet = ClassUtil.scanPackageByAnnotation("strategy",TaxTypeAnnotation.class);
        Optional.ofNullable(classSet).get().stream().filter(clazz -> clazz.isAnnotationPresent(TaxTypeAnnotation.class)).forEach(clazz ->{
            TaxTypeAnnotation taxTypeAnnotation = clazz.getAnnotation(TaxTypeAnnotation.class);
            try {
                taxStrategyMap.put(taxTypeAnnotation.taxType(),(TaxStrategy)clazz.newInstance());
            } catch (InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
        });
    }
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics