1.策略模式介绍
- 主要解决:在有多种算法相似的情况下,使用 if…else 所带来的复杂和难以维护。
- 优点: 1、算法可以自由切换。 2、避免大量的if…else。 3、扩展性良好
2.代码实现之
public interface IStrategy {
void addReward(Integer type);
}
import org.springframework.stereotype.Component;
@Component
public class StrategyServiceA implements IStrategy {
@Override
public void addReward(Integer type) {
System.out.println("=======Enter StrategyServiceA======="+type);
}
}
import org.springframework.stereotype.Component;
@Component
public class StrategyServiceB implements IStrategy {
@Override
public void addReward(Integer type) {
System.out.println("=======Enter StrategyServiceB======="+type);
}
}
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
private Map<String,IStrategy> strategyMap;
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);
}
}
}