springboot 策略模式示例

springboot 策略模式示例,第1张

springboot 策略模式示例 策略接口
package com.example.demo.strategy.service;

public interface Strategy {

    String doOperation();

}
策略实现
package com.example.demo.strategy.service.impl;

import com.example.demo.strategy.service.Strategy;
import org.springframework.stereotype.Component;

@Component("one")
public class StrategyOne implements Strategy {
    @Override
    public String doOperation() {
        return "one";
    }
}
package com.example.demo.strategy.service.impl;

import com.example.demo.strategy.service.Strategy;
import org.springframework.stereotype.Component;

@Component("two")
public class StrategyTwo implements Strategy {
    @Override
    public String doOperation() {
        return "two";
    }
}
策略工厂
package com.example.demo.strategy.factory;

import com.example.demo.strategy.service.Strategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Service
public class FactoryForStrategy {

    @Autowired
    Map strategyMap = new ConcurrentHashMap<>(16);

    public Strategy getStrategy(String component) {
        Strategy strategy = strategyMap.get(component);
        if (strategy == null) {
            throw new RuntimeException("no strategy defined");
        }
        return strategy;
    }

}
验证
package com.example.demo.strategy.controller;

import com.example.demo.strategy.factory.FactoryForStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/strategy")
public class StrategyController {

    private FactoryForStrategy factoryForStrategy;

    public StrategyController(FactoryForStrategy factoryForStrategy) {
        this.factoryForStrategy = factoryForStrategy;
    }

    @GetMapping("/get/{key}")
    public String strategy(@PathVariable("key") String key) {
        String result;
        try {
            result = factoryForStrategy.getStrategy(key).doOperation();
        } catch (Exception e) {
            result = e.getMessage();
        }
        return result;
    }


}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5683660.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-17
下一篇2022-12-17

发表评论

登录后才能评论

评论列表(0条)

    保存