目录
常规策略模式示例
- public abstract class Strategy {
-
- abstract void doSomething();
- }
-
- // 策略A
- public class AStrategy extends Strategy{
-
- @Override
- void doSomething() {
-
- }
- }
-
- // 策略B
-
- public class BStrategy extends Strategy{
-
- @Override
- void doSomething() {
-
- }
- }
函数式接口策略
定义函数方法
- @Slf4j
- public class Functions {
-
- public String strategyA(String resourceId){
- log.info(resourceId);
- return "A";
- }
-
- public String strategyB(String resourceId){
- log.info(resourceId);
- return "B";
- }
-
- public String strategyC(String resourceId){
- log.info(resourceId);
- return "C";
- }
- }
函数策略调用
- @Slf4j
- public class FunctionStrategy {
-
- private Functions functions = new Functions();
-
- /**
- * 函数式表
- */
- private Map<String, Function<String,String>> strategyMap = new HashMap<>();
-
- /**
- * 初始化函数匹配策略
- */
- public void init(){
- strategyMap.put("A",resourceId->functions.strategyA(resourceId));
- strategyMap.put("B",resourceId->functions.strategyB(resourceId));
- strategyMap.put("C",resourceId->functions.strategyC(resourceId));
- }
-
- /**
- * 获取结果
- * @param resourceId
- * @return
- */
- public String getResult(String resourceId){
- Function<String,String> result = strategyMap.get(resourceId);
- if(null != result){
- return result.apply(resourceId);
- }else{
- new RuntimeException("错误调用");
- }
- return null;
- }
-
- public static void main(String[] args) {
- FunctionStrategy functionStrategy = new FunctionStrategy();
- functionStrategy.init();
- log.debug("->{}",functionStrategy.getResult("A"));
- }
- }