栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot中的工厂模式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot中的工厂模式

说到工厂模式,先说说工厂模式是什么,有什么优点

平常我们在工作开发过程中,往往因为工期问题导致整体功能设计考虑的不够周到,导致后期迭代时发现需要原有功能流程基础上追加新功能时,需要耗费更多的成本,无法轻易推翻重构,接着便是将错就错,在if else之下再来一层elseif。通过设计模式去优化代码,达到代码的复用性,减少耦合,也就是我们常说的高内聚低耦合。

通过工厂模式可以把对象的创建和使用过程分割开来。比如说 Class A 想调用 Class B的方法,那么我们无需关心B是如何创建的,直接去工厂获取就行

那我们直接上代码举例一二:

代码结构:

 

工厂类:

@Component
public class ConnectionFactory implements ApplicationContextAware {

    public static Map connectionMap = new HashMap();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        //根据接口类型返回相应的所有bean
        Map map = applicationContext.getBeansOfType(IConnectionService.class);
        for (Map.Entry data: map.entrySet()) {
            List typeList = data.getValue().getType();
            if (CollUtil.isNotEmpty(typeList)) {
                for (String type : typeList) {
                    connectionMap.put(type, data.getValue());
                }
            }
        }

    }

    public static IConnectionService getConnectionService(String type) {
        IConnectionService connectionService = connectionMap.get(type);
        if (ObjectUtil.isNotNull(connectionService)) {
            return connectionService;
        } else {
            return null;
        }
    }


}

接口: 

public interface IConnectionService {
    
    Integer checkConnection(Connection connection);
    //获取类型
    List getType();

}

实现类一:

@Slf4j
@Service
public class JdbcConnectionServiceImpl implements IConnectionService {

    @Override
    public Integer checkConnection(Connection connection) {
        int res = 0;
        return res;
    }

    @Override
    public List getType() {
        List typeList = new ArrayList<>();
        typeList.add(PublicConstant.DATA_SOURCE_TYPE.MYSQL_TYPE);
        return typeList;
    }
}

调取:

@RequestMapping(value = "/checkConnection", method = RequestMethod.POST)
    @ResponseBody
    public String checkConnection(@RequestBody Connection connection) {
        if(StringUtils.isEmpty(connection.getDataSourceType())){
            return ReturnMapUtils.setFailedMsgRtnJsonStr("请传入数据源类型");
        }
        Integer integer = 0;
        //获取对应的Service对象
        IConnectionService service = ConnectionFactory.getConnectionService(connection.getDataSourceType());
        //检查连接是否成功
        if (ObjectUtil.isNotNull(service)) {
            integer = service.checkConnection(connection);
        }
        if (integer.equals(0)) {
            return ReturnMapUtils.setFailedMsgRtnJsonStr("连接失败");
        } else {
            return ReturnMapUtils.setSucceededMsgRtnJsonStr("连接成功");
        }
    }

=====================================================================

实现方式二:

//工厂类
import java.util.Map;
import com.google.common.collect.Maps;

public class TypeCheckFactory {
    private static Map strategyMap = Maps.newHashMap();

    public static TypeCheck getInvokeStrategy(String name) {

        return strategyMap.get(name);
    }

    public static void register(String name, TypeCheck stopCheck) {
        if (StringUtils.isEmpty(name) || stopCheck == null) {
            return;
        }
        strategyMap.put(name, stopCheck);
    }

    public static Map getStrategyMap() {
        return strategyMap;
    }
}
//接口
public interface TypeCheck extends InitializingBean {
    public String doInformationVerification();
    public String doInformationVerification(TypeFactoryBean checkFactoryBean);
}

 //实现类:

@Component
public class LSHAnalysisSimilerType implements StopCheck {


    @Override
    public String doInformationVerification() {
        return null;
    }

    @Override
    public String doInformationVerification(CheckFactoryBean checkFactoryBean) {

        return null;
    }


    //这个方法很关键,自动注入的关键,将当前对象注入进去当一个类实现这个接口之后,Spring启动时,初始化Bean时,若该Bean实现InitializingBean接口,则会自动调用afterPropertiesSet()方法,完成一些用户自定义的初始化操作
    @Override
    public void afterPropertiesSet() throws Exception {
        StopCheckFactory.register("LSHAnalysisSimilerType", this);
    }
}

//调取:

public static String typemetaInformation(List parentStopsVos, TypeVo toStopsVo,boolean checkFlag){
        String categories = getTypeCheckCategories(toStopsVo);
        TypeCheck typeCheck = StopCheckFactory.getInvokeStrategy(categories);        
        return typeCheck.doInformationVerification("123");
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/785690.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号