策略模式基本概念:
- 一个接口或者抽象类,里面两个方法(一个方法匹配类型,一个可替换的逻辑实现方法)
- 不同策略的差异化实现(就是说,不同策略的实现类)
使用策略模式替换判断,使代码更加优雅。
实现:
package com.demo.service.sjms;
import com.demo.utils.Result;
import java.util.Map;
public interface InvoiceKj {
Result service(Map param) ;
}
package com.demo.service.sjms;
import com.demo.utils.Result;
import com.demo.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Map;
@Slf4j
@Component("QDP-FP-10001")
public class InvoiceQdpFp10001 implements InvoiceKj {
@Override
public Result service(Map param) {
log.info("serviceid===>{}",param.get("serviceid"));
log.info("蓝票申请");
return ResultUtil.fail("不支持此开票类型!");
}
}
package com.demo.service.sjms;
import com.demo.utils.Result;
import com.demo.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Map;
@Slf4j
@Component("QDP-FP-10002")
public class InvoiceQdpFp10002 implements InvoiceKj {
@Override
public Result service(Map param) {
log.info("serviceid===>{}",param.get("serviceid"));
log.info("纸票待开号码查询");
return ResultUtil.fail("不支持此开票类型!");
}
}
package com.demo.service.sjms;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
@Component
public class InvoiceKjFactory {
@Autowired
Map<String, InvoiceKj> invoiceKjs = new ConcurrentHashMap<>(36);
public InvoiceKj getInstance(String serviceid) {
InvoiceKj invoiceKj = invoiceKjs.get(serviceid);
return invoiceKj;
}
}
package com.demo.service.sjms;
import com.demo.utils.Result;
import javax.servlet.http.HttpServletRequest;
public interface InvoiceOpenApiService {
/**
* 发票业务
* @param request
* @return
*/
Result<String> service(String serviceid, HttpServletRequest request);
}
package com.demo.service.sjms;
import cn.hutool.json.JSONObject;
import com.demo.utils.Result;
import com.demo.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
@Slf4j
@Service("invoiceOpenApiService")
public class InvoiceOpenApiServiceImpl implements InvoiceOpenApiService {
@Autowired
private InvoiceKjFactory invoiceKjFactory;
public Result<String> service(String serviceid, HttpServletRequest request) {
//1、处理请求参数
log.info("==> 同步开票对外接口,请求参数:{}",serviceid);
//3、校验应用及验签
JSONObject json = new JSONObject();
json.put("serviceid", serviceid);
//5、分发调用业务接口
Result ret = ResultUtil.success(invoiceKjFactory.getInstance(serviceid).service(json));
return ret;
}
}
调用
@GetMapping("/invoiceOpenApiService")
public Result bbb(String serviceid, HttpServletRequest request) {
return invoiceOpenApiService.service(serviceid, request);
}