栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot 策略模式示例

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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;
    }


}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/683101.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号