• JAVA 工具类Factory


    /**
     * @author yong.liu
     * @date 2020/7/30
     */
    public abstract class AbstractHandlerFactory<T,K extends HandlerSelector <T>> implements HandlerFactory <T,K>, BeanFactoryAware , InitializingBean {
    
        private Map<T, K> serviceMap;
    
        private ConfigurableListableBeanFactory beanFactory;
    
        @Override
        public K getService(T t) {
            return serviceMap.get(t);
        }
    
        @Override
        public void afterPropertiesSet() throws Exception {
    
            ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
            Type[] types = pt.getActualTypeArguments();
    
            Class<K> interfaceClazz = (Class<K>)types[1];
    
           // logger.info("可选服务初始化,服务接口为{},默认实现为{}", interfaceClazz.getName(), interfaceClazz.getName());
    
            Map<String, K> serviceBeanMap = beanFactory.getBeansOfType(interfaceClazz);
            serviceMap = new HashMap<T , K>(serviceBeanMap.size());
    
            for (K processor : serviceBeanMap.values()) {
    
                if (!(processor instanceof HandlerSelector)) {
                    throw new RuntimeException("实现类必须实现ProcessorSelector接口!");
                }
                // 如果已经存在相同受理机构的服务,则抛出错误
                HandlerSelector<T> selector = (HandlerSelector)processor;
    
                if (null != serviceMap.get(selector.getType())) {
                    throw new RuntimeException("已经存在Type【" + selector.getType() + "】的服务");
                }
    
                serviceMap.put(selector.getType(), processor);
    
            }
        }
    
        @Override
        public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
            if (beanFactory instanceof DefaultListableBeanFactory) {
                this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
            }
        }
    
    }
    
    public interface HandlerSelector<T> {
    
        /**
         * 获取选择器类型
         *
         * @return
         */
        T getType();
    }
    
    public interface HandlerFactory<T, K extends HandlerSelector<T>> {
        /**
         * 获取对应的服务
         *
         * @param t
         * @return
         */
        K getService(T t);
    }
    

    使用:

    public inteface SubsidyStatHandler implements HandlerSelector<String>{
        
       public void dosth()
    
    }
    
    
    @Service
    public class SubsidyStatHandlerFactroy extends AbstractHandlerFactory<Integer, SubsidyStatHandler> {
    
    }
    
  • 相关阅读:
    创建新用户
    发生tcp丢包(拥堵、超时)重传
    centos7装机和初步运维
    论上山和下山哪个费力
    一、Linux简介
    服务器设置FTP
    自定义部署资源服务器
    代码管理工具 Git
    远程连接工具rdcman
    dubbo学习(八)dubbo项目搭建--消费者(服务消费者)
  • 原文地址:https://www.cnblogs.com/lameclimber/p/14445913.html
Copyright © 2020-2023  润新知