应用场景
通常在我们需要new多个对象的时候,需要写很多个if else分支,根据不同场景来创建对象;我们可以通过初始化方式,批量创建对象。通常有如下3种形式:
先看一个具体场景例子,我们需要根据不同topic创建具体topic的实现子类,不想写几十个if/else;
方式一clazz.newInstance
DISPATCH_INFO(RetryBizEnum.DISPATCH_INFO.getValue(), FullBizCodeEnum.D1003, OrderSyncDispatchInfoConsumer.TOPIC, OrderSyncDispatchInfoConsumer.class);
/**
* 处理类bean
*/
private final Class<AbstractConsumerBase> dealBean;
ConsumerEnum(int bizType, FullBizCodeEnum bizCode, String topic, Class dealBean) {
this.bizType = bizType;
this.bizCode = bizCode;
this.topic = topic;
this.dealBean = (Class<AbstractConsumerBase>) dealBean;
}
for (ConsumerEnum type : ConsumerEnum.values()) {
Class<AbstractConsumerBase> clazz = type.getDealBean();
AbstractConsumerBase person = clazz.newInstance();
dealMap.put(type.getTopic(), person);
}
方式二-直接new方式
DISPATCH_INFO(RetryBizEnum.DISPATCH_INFO.getValue(), FullBizCodeEnum.D1003, OrderSyncDispatchInfoConsumer.TOPIC, new OrderSyncDispatchInfoConsumer());
/**
* 处理类bean
*/
private final AbstractConsumerBase dealBean;
ConsumerEnum(int bizType, FullBizCodeEnum bizCode, String topic, AbstractConsumerBase dealBean) {
this.bizType = bizType;
this.bizCode = bizCode;
this.topic = topic;
this.dealBean = (AbstractConsumerBase) dealBean;
}
for (ConsumerEnum type : ConsumerEnum.values()) {
dealMap.put(type.getTopic(), type.getDealBean());
}
后面使用静态工厂方式进行封装
package com.yougou.ordercenter.web.listener.kafka.topic.base;
import com.yougou.framework.logger.Logger;
import com.yougou.framework.logger.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
/**
* 静态工厂模式
*
* @author david
* @site www.belle.net.cn
* @company 百丽国际
* @Date 创建时间:2022-04-13 21:36
*/
public class ConsumerFactory {
private static final Logger logger = LoggerFactory.getLogger(ConsumerFactory.class);
// 把topic对应的具体处理类,关系映射
private static final Map<String, AbstractConsumerBase> dealMap = new HashMap<>(ConsumerEnum.values().length);
static {
try {
for (ConsumerEnum type : ConsumerEnum.values()) {
dealMap.put(type.getTopic(), type.getDealBean());
}
} catch (Exception e) {
logger.error("实例化ConsumerFactory工厂类异常" + e.getMessage(), e);
}
}
/**
* 通过topic获取具体实现类
*
* @param topic
* @return
*/
public static AbstractConsumerBase create(String topic) {
return dealMap.get(topic);
}
}