《策略模式》

1.策略模式介绍

  • 主要解决:在有多种算法相似的情况下,使用 if…else 所带来的复杂和难以维护。
  • 优点: 1、算法可以自由切换。 2、避免大量的if…else。 3、扩展性良好

2.代码实现之

  • 添加奖励的接口
public interface IStrategy {

    void addReward(Integer type);
}
  • 添加奖励实现A
import org.springframework.stereotype.Component;

@Component
public class StrategyServiceA implements IStrategy {
    @Override
    public void addReward(Integer type) {
        System.out.println("=======Enter StrategyServiceA======="+type);
    }
}
  • 添加奖励实现B
import org.springframework.stereotype.Component;

@Component
public class StrategyServiceB implements IStrategy {
    @Override
    public void addReward(Integer type) {
        System.out.println("=======Enter StrategyServiceB======="+type);
    }
}

  • 添加奖励实现C
import org.springframework.stereotype.Component;

@Component
public class StrategyServiceC implements IStrategy {
    @Override
    public void addReward(Integer type) {
        System.out.println("=======Enter StrategyServiceC======="+type);
    }
}

  • 添加奖励的枚举,用来标记code对应的奖励实现类,find方法用来寻找code对应的奖励实现类
public interface Reward {
    @Getter
    @AllArgsConstructor
    @NoArgsConstructor
    @ToString
    public enum Type implements Reward{
        T1(1,"strategyServiceA","游戏奖励"),
        T2(2,"strategyServiceB","签到奖励"),
        T3(3,"strategyServiceC","抽奖奖励");
        private Integer typeCode;
        private String  serviceType;
        private String  desc;
        public static Type findType(Integer incomingCode){
            Type[] types = Type.values();
            for (Type type: types) {
                if (type.getTypeCode().equals(incomingCode)){
                    return type;
                }
            }
            return null;
        }
    }
}

  • 策略模式测试
  • Spring高级特性,Key存的是IStrategy的实现类的Bean名称,value存的是对应的IStrategy实现类
@SpringBootTest(classes = {Application.class})
@RunWith(SpringRunner.class)
public class StrategyTest {
    @Autowired
    //Spring高级特性,Key存的是IStrategy的实现类的Bean名称,value存的是对应的IStrategy实现类
    private  Map<String,IStrategy> strategyMap;
    
    //模拟request请求中发过来的三种标志
    private Integer conditionA= 1;
    private Integer conditionB= 2;
    private Integer conditionC= 3;
    
    
    @Test
    public void test(){
        System.out.println("strategyMap = " + strategyMap);
        Reward.Type type = Reward.Type.findType(conditionB);
        if (type!=null){
            IStrategy iStrategy = strategyMap.get(type.getServiceType());
            iStrategy.addReward(conditionB);
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值