- 众所周知,项目中的业务处理可能一条线会有多种实现,例如一个下单就可能根据商品类型有多种处理的逻辑,此时,如果使用策略模式那么对该功能的拓展性、可读性都有明显的增强。
- 虽然说 if-else也可以实现策略模式,一人一个想法,策略模式也有无数的实现方式,本人自开发以来也写了很多套策略模式的实现,这次又写了一套自认优雅与拓展都很全面的方式去实现,各位看官请往下看。
- 首先定义自定义策略注解,再定义一个策略接口的(将需要实现的策略抽象在接口里),利用spring提供的IOC,将策略都注册到容器中,再首次调用策略时将所有的策略按照自定义注解的值存到对应的Map容器中,在业务方根据策略key获取实际的策略实现类调用方法。
- 以下是代码,首先定义一个策略模式处理handler,通用的,将所有策略模式需要用到的方法封装,减少调用方的编码。
- 核心base handler代码:使用了模板模式,直接调用抽象方法把具体实现交给子类,因为实际调用方是子类。
package com.central.common.handler;
import cn.hutool.core.map.MapUtil;
import com.central.common.utils.Assert;
import org.springframework.context.ApplicationContext;
import java.lang.annotation.Annotation;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
public abstract class BaseStrategyHandler<T, R extends Annotation> {
protected ApplicationContext applicationContext;
public BaseStrategyHandler(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
protected ConcurrentHashMap<String, Class<T>> container = new ConcurrentHashMap();
protected abstract Class<R> getStrategyAnnotationClass();
protected abstract Class<T> getStrategyInterface();
protected abstract List<String> getStrategyAnnotationValue(R strategyAnnotationEntity);
protected T getBean(Class<T> clazz) {
return applicationContext.getBean(clazz);
}
protected R getStrategyAnnotationEntity(Class<T> service) {
Class<R> strategyAnnotationClass = this.getStrategyAnnotationClass();
boolean annotationPresent = service.isAnnotationPresent(strategyAnnotationClass);
Assert.isTrue(!annotationPresent, "策略实现存在未加注解的异常");
return service.getAnnotation(strategyAnnotationClass);
}
protected void lazyInitContainer(){
ConcurrentHashMap<String, Class<T>> container = this.container;
Class<T> strategyInterface = this.getStrategyInterface();
applicationContext.getBeansOfType(strategyInterface).forEach((k, v) -> {
Class<T> service = (Class<T>) v.getClass();
R strategyAnnotationEntity = this.getStrategyAnnotationEntity(service);
List<String> strategyAnnotationValue = this.getStrategyAnnotationValue(strategyAnnotationEntity);
strategyAnnotationValue.stream().forEach(value -> container.putIfAbsent(value, service));
});
}
public T getStrategyEntity(String strategyKey) {
ConcurrentHashMap<String, Class<T>> container = this.container;
if (MapUtil.isEmpty(container)) {
this.lazyInitContainer();
}
return this.getBean(container.get(strategyKey));
}
}
- 子类handler代码:
package com.central.keep.strategy.orderRegRelation;
import com.central.common.dto.saveDto.OrderRegRelationSaveDto;
import com.central.common.enums.CommonEnum;
import com.central.common.handler.BaseStrategyHandler;
import com.central.common.utils.Assert;
import com.central.keep.annotation.OrderRegRelationAnnotation;
import com.central.keep.model.OrderRegRelation;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.List;
@Component
public class OrderRegRelationStrategyHandler extends BaseStrategyHandler<OrderRegRelationStrategy, OrderRegRelationAnnotation> {
public OrderRegRelationStrategyHandler(ApplicationContext applicationContext) {
super(applicationContext);
}
@Override
protected Class<OrderRegRelationAnnotation> getStrategyAnnotationClass() {
return OrderRegRelationAnnotation.class;
}
@Override
protected Class<OrderRegRelationStrategy> getStrategyInterface() {
return OrderRegRelationStrategy.class;
}
@Override
protected List<String> getStrategyAnnotationValue(OrderRegRelationAnnotation strategyAnnotationEntity) {
return Collections.singletonList(strategyAnnotationEntity.value().getCode());
}
public OrderRegRelation buildOrderRegRelation(OrderRegRelationSaveDto orderRegRelationSaveDto){
OrderRegRelationStrategy strategyEntity = this.getStrategyEntity(orderRegRelationSaveDto.getBizType());
Assert.isObjEmpty(strategyEntity, CommonEnum.ExceptionDesc.参数异常);
OrderRegRelation orderRegRelation = strategyEntity.setEntityAttributes(orderRegRelationSaveDto);
return orderRegRelation;
}
}
- 自定义注解代码:
package com.central.keep.annotation;
import com.central.common.enums.BizEnum;
import java.lang.annotation.*;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OrderRegRelationAnnotation {
BizEnum.BizTypeEnum value();
}
public class BizEnum {
@Getter
@AllArgsConstructor
public enum BizTypeEnum {
Keep_Curriculum("keep_curriculum", "keep 课程"),
Keep_Activity("keep_activity", "keep 活动"),
;
String code;
String desc;
}
}
- 策略接口类:
package com.central.keep.strategy.orderRegRelation;
import com.central.common.dto.saveDto.OrderRegRelationSaveDto;
import com.central.keep.model.OrderRegRelation;
public interface OrderRegRelationStrategy {
OrderRegRelation setEntityAttributes(OrderRegRelationSaveDto orderRegRelationSaveDto);
}
- 调用方代码例子:
public Boolean saveOrderRegRelation(OrderRegRelationSaveDto orderRegRelationSaveDto){
OrderRegRelation orderRegRelation = orderRegRelationStrategyHandler.buildOrderRegRelation(orderRegRelationSaveDto);
return this.save(orderRegRelation);
}
- 核心是BaseStrategyHandler ,分为容器(Map<策略值,策略实现>)、枚举(策略键定义)、接口(策略抽象与实现) ,配合spring的IOC就构成了这套策略模式的实现。拓展只需要多一个策略接口的实现即可。如果有多套策略需要实现,每套策略需要编写一个类似OrderRegRelationStrategyHandler 的子类。个人感觉整体逻辑会更清晰,可以作为一个项目的全局策略实现的底层来使用。
- 结尾附上完整的流程图,更容易理解一点,感谢网友给出意见。
- 这个说白了核心思想就是在注解里定义key值,然后按照key,value的结构把key值和对应的策略实现类放到ConcurrentHashMap里面。然后调用策略的时候根据你的不同的key值使用子类调用 BaseStrategyHandler#getStrategyEntity()的方法获取策略,然后直接用具体的策略实现类去调用你的不同的策略。
留言:老婆做了一个小红书账号,全是瓷砖方面的干货,大佬们如果有需求或者有兴趣可以移步了解一下,嘻嘻~
小红书地址,GO GO GO!!!