1.定义
对一系列算法进行封装并定义一个抽象的接口,通过继承该接口实现具体的算法。策略模式让算法可以独立于使用它的客户而改变。 Spring 容器中使用配置可以灵活的替换掉接口的实现类就是策略模式最常见的应用。(使用策略模式可以减少大量的if,else if)
缺点:1)客户端必须知道所有的策略类,并自行决定使用哪一个策略类;2)略模式造成很多的策略类。
使用场景:
(1) 针对同一类型问题的多种处理方式,仅仅是具体行为有差别时;
(2) 出现同一抽象类有多个子类,而又需要使用 if-else 或者 switch-case 来选择具体
子类时。
2.创建一个空的springboot工程
3.创建接口Province
package com.example.demo.strategy;
public interface Province {
public boolean support(String flag);
public void handler();
}
4.创建实现类JS
package com.example.demo.strategy;
import org.springframework.stereotype.Component;
import java.util.Objects;
@Component
public class JS implements Province{
private static String flag = "JS";
@Override
public boolean support(String flag) {
return Objects.equals(flag, JS.flag);
}
@Override
public void handler() {
System.out.println("江苏欢迎你!!!");
}
}
5.创建实现类GD
package com.example.demo.strategy;
import org.springframework.stereotype.Component;
import java.util.Objects;
@Component
public class GD implements Province{
private static String flag = "GD";
@Override
public boolean support(String flag) {
return Objects.equals(flag, GD.flag);
}
@Override
public void handler() {
System.out.println("广东欢迎你!!!");
}
}
6.创建实现类BJ
package com.example.demo.strategy;
import org.springframework.stereotype.Component;
import java.util.Objects;
@Component
public class BJ implements Province{
private static String flag = "BJ";
@Override
public boolean support(String flag) {
return Objects.equals(flag, BJ.flag);
}
@Override
public void handler() {
System.out.println("北京欢迎你!!!");
}
}
7.创建StrategyController
package com.example.demo.controller;
import com.example.demo.strategy.Province;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
public class StrategyController {
@Autowired
private ApplicationContext applicationContext;
@RequestMapping(value = "strategy")
public void strategy(@RequestParam String position) {
//获取Province接口的所有实现类
Map<String, Province> beansOfType = applicationContext.getBeansOfType(Province.class);
beansOfType.forEach((k,v)->{
if (v.support(position)) {
v.handler();
}
});
}
}