提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
这里虚拟一个业务需求,让大家容易理解。假设有一个订单系统,里面的一个功能是根据订单的不同类型作出不同的处理。
一、传统方式实现
订单实体:
public class OrderDTO {
private String code;
private BigDecimal price;
/**
* 订单类型
* 1:普通订单;
* 2:团购订单;
* 3:促销订单;
*/
private String type;
// ... 省略 get / set ...
}
接口:
public interface IOrderService {
/**
* 根据订单的不同类型作出不同的处理
*
* @param dto 订单实体
* @return 为了简单,返回字符串
*/
String handle(OrderDTO dto);
}
传统方式实现:
public class OrderServiceImpl implements IOrderService {
@Override
public String handle(OrderDTO dto) {
String type = dto.getType();
if ("1".equals(type)) {
return "处理普通订单";
} else if ("2".equals(type)) {
return "处理团购订单";
} else if ("3".equals(type)) {
return "处理促销订单";
}
return null;
}
}
二、策略方式实现
1.实现思路
- 将不同业务类型的逻辑分别在不同的类中进行实现
- 所有的具体实现都继承同一个抽象类
- 在项目启动的过程中,将所有的实现类以key/value的方式存储到一个Map中
- 程序调用时会根据订单的类型,去找对应的实现进行调用
2. 代码实现
具体类型实现
@Component
@HandlerType("1")
public class NormalHandler extends AbstractHandler {
@Override
public String handle(OrderDTO dto) {
return "处理普通订单";
}
}
@Component
@HandlerType("2")
public class GroupHandler extends AbstractHandler {
@Override
public String handle(OrderDTO dto) {
return "处理团购订单";
}
}
@Component
@HandlerType("3")
public class PromotionHandler extends AbstractHandler {
@Override
public String handle(OrderDTO dto) {
return "处理促销订单";
}
}
通过自定义注解来标识对应的订单类型。
自定义注解 @HandlerType
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface HandlerType {
String value();
}
定义是存储bean的容器:
public class HandlerContext {
private Map<String, Class> handlerMap;
public HandlerContext(Map<String, Class> handlerMap) {
this.handlerMap = handlerMap;
}
public AbstractHandler getInstance(String type) {
Class clazz = handlerMap.get(type);
if (clazz == null) {
throw new IllegalArgumentException("not found handler for type: " + type);
}
return (AbstractHandler) BeanTool.getBean(clazz);
}
}
将具体实现类,扫描存储到HandlerContext .handlerMap中:
@Component
@SuppressWarnings("unchecked")
public class HandlerProcessor implements BeanFactoryPostProcessor {
private static final String HANDLER_PACKAGE = "com.cipher.handler_demo.handler.biz";
/**
* 扫描@HandlerType,初始化HandlerContext,将其注册到spring容器
*
* @param beanFactory bean工厂
* @see HandlerType
* @see HandlerContext
*/
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
Map<String, Class> handlerMap = Maps.newHashMapWithExpectedSize(3);
ClassScaner.scan(HANDLER_PACKAGE, HandlerType.class).forEach(clazz -> {
// 获取注解中的类型值
String type = clazz.getAnnotation(HandlerType.class).value();
// 将注解中的类型值作为key,对应的类作为value,保存在Map中
handlerMap.put(type, clazz);
});
// 初始化HandlerContext,将其注册到spring容器中
HandlerContext context = new HandlerContext(handlerMap);
beanFactory.registerSingleton(HandlerContext.class.getName(), context);
}
}
抽象类定义:
public abstract class AbstractHandler {
abstract public String handle(OrderDTO dto);
}
调用实现:
@Service
public class OrderServiceV2Impl implements IOrderService {
@Autowired
private HandlerContext handlerContext;
@Override
public String handle(OrderDTO dto) {
AbstractHandler handler = handlerContext.getInstance(dto.getType());
return handler.handle(dto);
}
}
3. 用到的工具类
BeanTool
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* Bean工具类<br>
* 在非spring管理的类中获取spring注册的bean
*
*/
@Component
public class BeanTool implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
if (applicationContext == null) {
applicationContext = context;
}
}
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
public static <T> T getBean(Class<T> clazz) {
return applicationContext.getBean(clazz);
}
}
ClassScaner
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.util.StringUtils;
import org.springframework.util.SystemPropertyUtils;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
/**
*/
public class ClassScaner implements ResourceLoaderAware {
private final List<TypeFilter> includeFilters = new LinkedList<TypeFilter>();
private final List<TypeFilter> excludeFilters = new LinkedList<TypeFilter>();
private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
private MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver);
@SafeVarargs
public static Set<Class<?>> scan(String[] basePackages, Class<? extends Annotation>... annotations) {
ClassScaner cs = new ClassScaner();
if (ArrayUtils.isNotEmpty(annotations)) {
for (Class anno : annotations) {
cs.addIncludeFilter(new AnnotationTypeFilter(anno));
}
}
Set<Class<?>> classes = new HashSet<>();
for (String s : basePackages) {
classes.addAll(cs.doScan(s));
}
return classes;
}
@SafeVarargs
public static Set<Class<?>> scan(String basePackages, Class<? extends Annotation>... annotations) {
return ClassScaner.scan(StringUtils.tokenizeToStringArray(basePackages, ",; \t\n"), annotations);
}
public final ResourceLoader getResourceLoader() {
return this.resourcePatternResolver;
}
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourcePatternResolver = ResourcePatternUtils
.getResourcePatternResolver(resourceLoader);
this.metadataReaderFactory = new CachingMetadataReaderFactory(
resourceLoader);
}
public void addIncludeFilter(TypeFilter includeFilter) {
this.includeFilters.add(includeFilter);
}
public void addExcludeFilter(TypeFilter excludeFilter) {
this.excludeFilters.add(0, excludeFilter);
}
public void resetFilters(boolean useDefaultFilters) {
this.includeFilters.clear();
this.excludeFilters.clear();
}
public Set<Class<?>> doScan(String basePackage) {
Set<Class<?>> classes = new HashSet<>();
try {
String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
+ org.springframework.util.ClassUtils
.convertClassNameToResourcePath(SystemPropertyUtils
.resolvePlaceholders(basePackage))
+ "/**/*.class";
Resource[] resources = this.resourcePatternResolver
.getResources(packageSearchPath);
for (int i = 0; i < resources.length; i++) {
Resource resource = resources[i];
if (resource.isReadable()) {
MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource);
if ((includeFilters.size() == 0 && excludeFilters.size() == 0) || matches(metadataReader)) {
try {
classes.add(Class.forName(metadataReader
.getClassMetadata().getClassName()));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
} catch (IOException ex) {
throw new BeanDefinitionStoreException(
"I/O failure during classpath scanning", ex);
}
return classes;
}
protected boolean matches(MetadataReader metadataReader) throws IOException {
for (TypeFilter tf : this.excludeFilters) {
if (tf.match(metadataReader, this.metadataReaderFactory)) {
return false;
}
}
for (TypeFilter tf : this.includeFilters) {
if (tf.match(metadataReader, this.metadataReaderFactory)) {
return true;
}
}
return false;
}
}