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

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部