策略接口

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<String, Strategy> 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;
    }


}

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐