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 {

    @Autowired
    private Client client;

    @Override
    public 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 {

    @Autowired
    private Client client;

    @Override
    public 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 {
    @Autowired
    Map<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 {

    @Autowired
    FactoryForStrategy 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

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值