欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

springboot 实现策略模式

发布时间:2024/9/16 44 豆豆
生活随笔 收集整理的这篇文章主要介绍了 springboot 实现策略模式 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

撸了今年阿里、头条和美团的面试,我有一个重要发现.......>>>

需求

根据Restful API,前端传给后台的参数,动态的调用具体的service。不用手动写if else进行判断。

service

UserService.java

package com.vincent.service;public interface UserService {String getGender(String gender); }

两个service实现类分别实现这个UserService接口

FemaleServiceImpl.java

package com.vincent.service.impl;import com.vincent.service.UserService; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.Client; import org.elasticsearch.index.query.QueryBuilders; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;@Service("female") public class FemaleServiceImpl implements UserService {@Autowiredprivate Client client;@Overridepublic String getGender(String name) {SearchResponse test = client.prepareSearch("test").setQuery(QueryBuilders.boolQuery().must(QueryBuilders.termQuery("name", name))).setSize(0).get();System.out.println("female" + test.getHits().totalHits);return null;} }

MaleServiceImpl.java

package com.vincent.service.impl;import com.vincent.service.UserService; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.Client; import org.elasticsearch.index.query.QueryBuilders; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;@Service("male") public class MaleServiceImpl implements UserService {@Autowiredprivate Client client;@Overridepublic String getGender(String name) {SearchResponse test = client.prepareSearch("test").setQuery(QueryBuilders.boolQuery().must(QueryBuilders.termQuery("name", name))).setSize(0).get();System.out.println("male:" + test.getHits().totalHits);return null;} }

如何自动根据参数选择具体的UserService实现类?

新建FactoryForStratge.java

package com.vincent.service.impl;import com.vincent.service.UserService; 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 {@AutowiredMap<String, UserService> strategys = new ConcurrentHashMap<>(3);public UserService getStrategy(String component) throws Exception{UserService strategy = strategys.get(component);if(strategy == null) {throw new RuntimeException("no strategy defined");}return strategy;}}

根据bean的name来选择。

工厂类FactoryStrategy负责创建策略的工厂,代码比较简单,比较关键的一点是AutoWired一个Map<String, UserService> 这个会在初始化的时候将所有的UserService自动加载到Map中,是不是很方便。使用concurrentHashMap是防止多线程操作的时候出现问题。

UserController.java

package com.vincent.controller;import com.vincent.service.UserService; import com.vincent.service.impl.FactoryForStrategy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController;@RestController public class UserController {@AutowiredFactoryForStrategy factoryForStrategy;@GetMapping("/gender2/{gender}/{name}")public String getGender2(@PathVariable String gender, @PathVariable String name) {try {UserService strategy = factoryForStrategy.getStrategy(gender);String gender1 = strategy.getGender(name);return "success";} catch (Exception e) {e.printStackTrace();return "failed";}}}

这样就可以根据参数来选择具体的service实现类了。

代码:https://github.com/vincentduan/springboot-test

总结

以上是生活随笔为你收集整理的springboot 实现策略模式的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。