
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;
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)