- 抽象类
java
/**
* 策略模式:不同类型选择不同的实现策略
* */
public interface AbstractStrategy {
/**
* 模版模式:不同策略实现同一接口的共性部分(公共方法)
* */
default void commentMeth(){
System.out.println("模版方法");
}
void handle(Object object);
}
2.抽象的实现
java
@Service
public class AchieveOneStrategy implements AbstractStrategy{
@Override
public void handle(Object obj) {
}
}
java
@Service
public class AchieveTwoStrategy implements AbstractStrategy{
@Override
public void handle(Object object) {
}
}
java
@Service
public class AchieveThreeStrategy implements AbstractStrategy{
@Override
public void handle(Object object) {
}
}
3.枚举
java
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.工厂
java
/**
* 工厂模式:根据不同类型创建不同实例
* */
@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);
}
}