说到工厂模式,先说说工厂模式是什么,有什么优点
平常我们在工作开发过程中,往往因为工期问题导致整体功能设计考虑的不够周到,导致后期迭代时发现需要原有功能流程基础上追加新功能时,需要耗费更多的成本,无法轻易推翻重构,接着便是将错就错,在if else之下再来一层elseif。通过设计模式去优化代码,达到代码的复用性,减少耦合,也就是我们常说的高内聚低耦合。
通过工厂模式可以把对象的创建和使用过程分割开来。比如说 Class A 想调用 Class B的方法,那么我们无需关心B是如何创建的,直接去工厂获取就行
那我们直接上代码举例一二:
代码结构:
工厂类:
@Component
public class ConnectionFactory implements ApplicationContextAware {
public static Map<String, IConnectionService> connectionMap = new HashMap<String, IConnectionService>();
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
//根据接口类型返回相应的所有bean
Map<String, IConnectionService> map = applicationContext.getBeansOfType(IConnectionService.class);
for (Map.Entry<String, IConnectionService> data : map.entrySet()) {
List<String> 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<String> getType();
}
实现类一:
@Slf4j
@Service
public class JdbcConnectionServiceImpl implements IConnectionService {
@Override
public Integer checkConnection(Connection connection) {
int res = 0;
return res;
}
@Override
public List<String> getType() {
List<String> 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<String, TypeCheck> 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<String, TypeCheck> getStrategyMap() {
return strategyMap;
}
}
//实现类:
@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<TypeVo> parentStopsVos, TypeVo toStopsVo,boolean checkFlag){
String categories = getTypeCheckCategories(toStopsVo);
TypeCheck typeCheck = StopCheckFactory.getInvokeStrategy(categories);
return typeCheck.doInformationVerification("123");
}
转载链接:https://blog.csdn.net/Alex_81D/article/details/123797391?spm=1001.2014.3001.5506