策略模式+模版模式+工厂模式
1. 抽象类
/**
* 策略模式:不同类型选择不同的实现策略
* */
public interface AbstractStrategy {
/**
* 模版模式:不同策略实现同一接口的共性部分(公共方法)
* */
default void commentMeth(){
System.out.println("模版方法");
}
void handle(Object object);
}
2.抽象的实现
@Service
public class AchieveOneStrategy implements AbstractStrategy{
@Override
public void handle(Object obj) {
}
}
@Service
public class AchieveTwoStrategy implements AbstractStrategy{
@Override
public void handle(Object object) {
}
}
@Service
public class AchieveThreeStrategy implements AbstractStrategy{
@Override
public void handle(Object object) {
}
}
3.枚举
public enum StrategyTypeEnum {
ONE_STRATEGY(0,AchieveOneStrategy.class),
TWO_STRATEGY(1,AchieveTwoStrategy.class),
THREE_STRATEGY(2,AchieveThreeStrategy.class),
;
Integer type;
Class<? extends AbstractStrategy> aClass;
StrategyTypeEnum(Integer type, Class<? extends AbstractStrategy> aClass){
this.type = type;
this.aClass = aClass;
}
}
4.工厂
/**
* 工厂模式:根据不同类型创建不同实例
* */
@Service
public class StrategyFactory {
@Autowired
private ApplicationContext applicationContext;
static HashMap<Integer, Class<? extends AbstractStrategy>> strategyHashMap = new HashMap<>();
static {
for (StrategyTypeEnum value : StrategyTypeEnum.values()) {
strategyHashMap.put(value.type, value.aClass);
}
}
public AbstractStrategy executeStrategy(Integer flag){
Class<? extends AbstractStrategy> aClass = strategyHashMap.get(flag);
return applicationContext.getBean(aClass);
}
}
原文地址:https://blog.csdn.net/m0_57801749/article/details/142335321
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!