springboot中如何使用策略模式干掉if—else

常见if-else案列

public class OrderServiceImpl implements OrderService {

@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;
}

}

策略模式实现

@Service
public class OrderServiceImpl implements OrderService {

@Autowired
private HandlerContext handlerContext;

@Override
public String handle(OrderDTO dto) {
    AbstractHandler handler = handlerContext.getInstance(dto.getType());
    return handler.handle(dto);
}

}

自定义注解 @HandlerType

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface HandlerType {

String value();

}

抽象处理器 AbstractHandler:

public abstract class AbstractHandler {
abstract public String handle(OrderDTO dto);
}

业务处理

@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 "处理促销订单";
}

}

我们将核心的功能封装在HandlerProcessor类中,完成上面的功能

HandlerProcessor: com.cipher.handler.biz是业务处理类的包路劲

@Component
@SuppressWarnings(“unchecked”)
public class HandlerProcessor implements BeanFactoryPostProcessor {

private static final String HANDLER_PACKAGE = "com.cipher.handler.biz";

/**
 * 扫描@HandlerType,初始化HandlerContext,将其注册到spring容器
 *
 * @param beanFactory bean工厂
 * @see HandlerType
 * @see HandlerContext
 */
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    Map 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);
}

}

ClassScaner:扫描工具类源码

public class ClassScaner implements ResourceLoaderAware {

private final List includeFilters = new LinkedList();
private final List excludeFilters = new LinkedList();

private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
private MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver);

@SafeVarargs
public static Set> scan(String[] basePackages, Class... annotations) {
    ClassScaner cs = new ClassScaner();

    if (ArrayUtils.isNotEmpty(annotations)) {
        for (Class anno : annotations) {
            cs.addIncludeFilter(new AnnotationTypeFilter(anno));
        }
    }

    Set> classes = new HashSet<>();
    for (String s : basePackages) {
        classes.addAll(cs.doScan(s));
    }

    return classes;
}

@SafeVarargs
public static Set> scan(String basePackages, Class... 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> doScan(String basePackage) {
    Set> 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;
}

}

Bean工具类

Bean工具类
在非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 getBean(Class clazz) {
    return applicationContext.getBean(clazz);
}

}

核心工作已经完成,现在看看HandlerContext如何获取对应的处理器:

HandlerContext:

处理器上下文,根据类型获取相应的处理器

@SuppressWarnings(“unchecked”)
public class HandlerContext {

private Map handlerMap;

public HandlerContext(Map 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);
}

}

你可能感兴趣的:(java杂谈)