• 策略模式经典实战


    策略模式经典实战

    /**
    * 接口
    */
    public interface ITestService {
    public String sayHello();
    }


    //定义一个抽象,处理公共部分
    public class AbstractTest {
    public void commonHandler(){
    System.out.println("AbstractTest#common");
    }
    }

    /**
    * 策略一
    */
    @Service("aFaceServiceStrategyImpl")
    public class ATestServiceStrategyImpl extends AbstractTest implements ITestService {
    @Override
    public String sayHello() {
    commonHandler();
    return "AFaceServiceImpl.sayHello()";
    }
    }

    /**
    * 策略二
    */
    @Service("bFaceServiceStrategyImpl")
    public class BTestServiceStrategyImpl extends AbstractTest implements ITestService {
    @Override
    public String sayHello() {
    commonHandler();
    return "BFaceServiceImpl.sayHello()";
    }
    }

    /**
    * 工厂类
    * 通过入参type选择不同的策略执行
    */
    @Component
    public class ProcessFactroy implements ApplicationContextAware {

    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext arg0) throws BeansException {//此处特别注意,默认的入参是applicationContext,此处必须修改这个入参,比如改成arg0,否则启动项目会报错
            applicationContext = arg0;
    }

    private static Map<String, ITestService> map = Maps.newHashMap();
    @PostConstruct
    public void register(){
    map.put("a",applicationContext.getBean(ATestServiceStrategyImpl.class));
    map.put("b",applicationContext.getBean(BTestServiceStrategyImpl.class));
    }

    public static ITestService getProcess(String type){
    ITestService iTestService = map.get(type);
    if(iTestService == null){
    throw new RuntimeException("参数不合法");
    }
    return iTestService;
    }

    }


    /**
    * 控制层,通过ProcessFactroy 工厂选择不同策略执行
    */
    @RestController
    public class TestContoller {
    @RequestMapping(value = "/test",method = RequestMethod.GET)
    public String faceRecognition(@RequestParam("type") String type){
    ITestService iTestService = ProcessFactroy.getProcess(type);
    return iTestService.sayHello();
    }
    }








  • 相关阅读:
    [SDOI2006] 保安站岗
    [NOIP2003] 传染病控制
    [USACO13OPEN] 照片Photo
    [HNOI/AHOI2018] 道路
    [TJOI2007] 线段
    [HAOI2009] 逆序对数列
    codeforces|CF1054D Changing Array
    hihoCoder 1785
    luogu 1712
    luogu 3248
  • 原文地址:https://www.cnblogs.com/wenhuang/p/13514369.html
Copyright © 2020-2023  润新知