java设计模式-策略模式+反射实践

1、定义接口处理器:

public interface ITaskAbnormalDealHandler {
    void handlerTaskDeal(String obj);

    void registerDealHandler();
}

定义工厂,策略模式注册:

import com.zxzz.wbt.utils.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
 
@Slf4j
public class MqttMessageDealHanlderFactory {
    
    final static Map<String, IMqttMessageDealHandler> dealHandlerHashMap = new HashMap<>();
    //项目启动,初始化注册
    static {
        autoRegisterDealHandleStrategy();
    }

    public MqttMessageDealHanlderFactory() {
    }

    /**
     * 根据枚举获取处理器
     *
     * @param key
     * @return
     */
    public static IMqttMessageDealHandler getDealHandleStrategy(String key) {
        return dealHandlerHashMap.get(key);
    }

    /**
     * 处理器
     *
     * @param key
     * @param dealHandler
     */
    public static void registerDealHandler(String key, IMqttMessageDealHandler dealHandler) {
        dealHandlerHashMap.put(key, dealHandler);
    }


    /**
     * 自动注册策略
     * 反射找类的同时,去注册handler
     */
    private static void autoRegisterDealHandleStrategy() {
        try {
            // 通过反射找到所有的策略子类进行注册
            Reflections reflections = new Reflections(new ConfigurationBuilder()
                    .setUrls(ClasspathHelper.forPackage(IMqttMessageDealHandler.class.getPackage().getName()))
                    .setScanners(new SubTypesScanner()));
            Set<Class<? extends IMqttMessageDealHandler>> taskClassSet = reflections.getSubTypesOf(IMqttMessageDealHandler.class);

            if (taskClassSet != null) {
                for (Class<?> clazz : taskClassSet) {
                    IMqttMessageDealHandler delayDealHandler = (IMqttMessageDealHandler) SpringContextUtil.getBean(clazz);
                    // 调用策略的自注册方法
                    delayDealHandler.registerMqttDealHandler();
                }
            }
        } catch (Exception e) {
            log.error("自动注册策略错误:{}", e.getMessage());
        }
    }
}

获取上下文工具类:

import org.springframework.context.ApplicationContext;

/**
 * @author bluekingzmm
 * @desc 获取上下文工具类
 * @date 2021年09月28日
 */
public class SpringContextUtil {
    private static ApplicationContext applicationContext;

    /**
     * 获取上下文
     *
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 设置上下文
     *
     * @param applicationContext
     */
    public static void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextUtil.applicationContext = applicationContext;
    }

    /**
     * 通过名字获取上下文中的bean
     *
     * @param name
     * @return
     */
    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    /**
     * 通过类型获取上下文中的bean
     *
     * @param requiredType
     * @return
     */
    public static Object getBean(Class<?> requiredType) {
        return applicationContext.getBean(requiredType);
    }
}
@Component
public class SpringUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext = null;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtil.applicationContext = applicationContext;
    }
    public static <T> T getBean(Class<T> cla) {
        return applicationContext.getBean(cla);
    }
    public static <T> T getBean(String name, Class<T> cal) {
        return applicationContext.getBean(name, cal);
    }
    public static Object getBean(String name){
        return applicationContext.getBean(name);
    }
    public static String getProperty(String key) {
        return applicationContext.getBean(Environment.class).getProperty(key);
    }
}
 private TaskService getService(){
        return SpringUtil.getBean(this.getClass());   //SpringUtil工具类见下面代码
    }

实现类handler处理器:

@Slf4j
@Service
public class TaskAbnormalRuleRetToSub implements ITaskAbnormalDealHandler {

    @Override
    public void handlerTaskDealAbnormal(Obj obj) {
       ......
    }

    @Override
    public void registerTaskAbnormalDealHandler() {
        TaskAbnormalDealHanlderFactory.registerTaskAbnormalDealHandler(AbnormalConfigOperateEnum.RETURN_TO_APPLICANT.getCode(), this);
    }
}

调用:
ITaskAbnormalDealHandler iTaskAbnormalDealHandler = TaskAbnormalDealHanlderFactory.getEndNodeDealHandleStrategy(abnormalConfigOperate);
if (null == iTaskAbnormalDealHandler) {
    continue;
}
iTaskAbnormalDealHandler.handlerTaskDealAbnormal(Obj obj);

main方法,需要加

public static void main(String[] args) {
    ApplicationContext context = SpringApplication.run(wbtApplication.class, args);
    SpringContextUtil.setApplicationContext(context);
    logger.info("启动成功!!");
}

maven依赖:

<dependency>
    <groupId>org.reflections</groupId>
    <artifactId>reflections</artifactId>
    <version>0.9.10</version>
</dependency>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值