java 使用反射和策略模式 优化多个if else

说明 : 以汽车品牌为例,比如大众汽车,和本田汽车, 车都有各自的颜色及价格  ,以此为背景,进行代码实例演示

包结构

java 使用反射和策略模式 优化多个if else_第1张图片

代码演示

汽车类型枚举

package com.cn.java.base.common.enums;

/**
 * @author hg
 * @desc 1.0
 * @date 2020/5/31 16:18
 */
public enum CarTypeEnum {

    HONDA_CAR(1, "本田"),
    VW(2, "大众"),
    UNDEFINE(-1, "未定义异常信息");

    private int code;
    private String msg;
    CarTypeEnum(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }
    public static String msg(int code) {
        for (CarTypeEnum m : CarTypeEnum.values()) {
            if (m.getCode() == code) {
                return m.getMsg();
            }
        }
        return UNDEFINE.getMsg();
    }
    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }

}

自定义注解,绑定策略实现类

package com.cn.java.base.common.annotation;

/**
 * @author hg
 * @desc 1.0
 * @date 2020/5/31 15:33
 */
import com.cn.java.base.common.enums.CarTypeEnum;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface StrategyType {

    //策略名
    CarTypeEnum carType();
}

step1: 首先定义通用策略接口   CarBaseStrategy

package com.cn.java.base.strategy;

/**
 * @author hg
 * @desc 1.0
 * @date 2020/5/31 16:04
 */
public interface CarBaseStrategy {

    /**
     * 汽车颜色
     * @return
     */
    String carColor();

    /**
     * 汽车价格
     * @return
     */
    String carPrice();

}

step2: 定义各个汽车实现

本田汽车实现

package com.cn.java.base.strategy.car;

import com.cn.java.base.common.annotation.StrategyType;
import com.cn.java.base.common.enums.CarTypeEnum;
import com.cn.java.base.strategy.CarBaseStrategy;
import org.springframework.stereotype.Component;

/**
 * @author hg
 * @desc 1.0 本田汽车
 * @date 2020/5/31 16:10
 */
@Component
@StrategyType(carType = CarTypeEnum.HONDA_CAR)
public class HondaCar implements CarBaseStrategy {

    @Override
    public String carColor() {
        return "本田铂金灰";
    }

    @Override
    public String carPrice() {
        return "价格 - 15W";
    }
}

大众汽车实现

package com.cn.java.base.strategy.car;

import com.cn.java.base.common.annotation.StrategyType;
import com.cn.java.base.common.enums.CarTypeEnum;
import com.cn.java.base.strategy.CarBaseStrategy;
import org.springframework.stereotype.Component;

/**
 * @author hg
 * @desc 1.0  大众汽车
 * @date 2020/5/31 16:09
 */
@Component
@StrategyType(carType = CarTypeEnum.VW)
public class VwCar implements CarBaseStrategy {

    @Override
    public String carColor() {
        return "大众铂金灰";
    }

    @Override
    public String carPrice() {
        return "价格 - 15W";
    }
}

step3: 定义策略实例缓存容器

package com.cn.java.base.strategy;

import java.util.HashMap;
import java.util.Map;

/**
 * @author hg
 * @desc 1.0
 * @date 2020/5/31 16:05
 */
public class CacheCollection {

    private static Map ALL_DATA_SOURCE;

    static {
        ALL_DATA_SOURCE = new HashMap<>(100);
    }

    /**
     * 根据策略名获取 Class
     * @param dsType
     * @return
     */
    public static Class getDS(String dsType) {
        return ALL_DATA_SOURCE.get(dsType);
    }
    /**
     * 策略名为 key,Class 为 value
     */
    public static void putClass(String dsType,Class clazz){
        ALL_DATA_SOURCE.put(dsType,clazz);
    }

}

step4: springboot启动 初始化策略实例,并加载至容器中

package com.cn.java.base.strategy;

import com.cn.java.base.common.annotation.StrategyType;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.net.URL;

/**
 * @author hg
 * @desc 1.0
 * @date 2020/5/31 16:05
 */
@Component
public class InitDataSource {

    private String packageVo="com.cn.java.base.strategy.car";

    @PostConstruct
    public void init() {
        initAllDataSourceType(packageVo);
    }

    private void initAllDataSourceType(String packageVo) {
        URL url = this.getClass().getClassLoader().getResource(packageVo.replace(".", "/"));
        File dir = new File(url.getFile());
        for (File file : dir.listFiles()) {
            if (file.isDirectory()) {
                continue;
            } else {
                String className = packageVo + "." + file.getName().replace(".class", "");

                try {
                    Class clazz = Class.forName(className);// class cn.haoxy.ref.inter.impl.faceRecognition
                    //判断这个类上是否存在指定的注解
                    if (clazz.isAnnotationPresent(StrategyType.class)) {
                        //如果存在,得到此注解的value值
                        StrategyType dataSourceType = clazz.getAnnotation(StrategyType.class);
                        //放入容器   此位置使用枚举类型约定策略类型
                        CacheCollection.putClass(dataSourceType.carType().name(), clazz);
                    }
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                    continue;
                }
            }
        }
    }

}

step5: 定义策略调度器

package com.cn.java.base.strategy;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author hg
 * @desc 1.0
 * @date 2020/5/31 16:07
 */
@Component
public class StrategyManager implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    public CarBaseStrategy getStrategyInstance(String dsType) {
        Class clazz = CacheCollection.getDS(dsType);
        CarBaseStrategy crBaseStrategy = (CarBaseStrategy) applicationContext.getBean(clazz);
        return crBaseStrategy;
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

step6: 调度策略

package com.cn.java.base.controller;

import com.cn.java.base.common.enums.CarTypeEnum;
import com.cn.java.base.common.utils.R;
import com.cn.java.base.strategy.CarBaseStrategy;
import com.cn.java.base.strategy.StrategyManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author hg
 * @desc 1.0
 * @date 2020/5/31 16:34
 */
@Slf4j
@RestController
@RequestMapping("strategy")
public class StrategyController {


    @Autowired
    private StrategyManager strategyManager;

    @RequestMapping("strategyTest")
    public R strategyTest(){
        CarBaseStrategy car = strategyManager.getStrategyInstance(CarTypeEnum.HONDA_CAR.name());
        System.out.println(car.carColor());
        System.out.println(car.carPrice());
        return R.ok().put("data","success");
    }

}

输出结果

java 使用反射和策略模式 优化多个if else_第2张图片

你可能感兴趣的:(java,高级基础系列)