JAVA 中 API 链的最佳设计模式

goo*_*ump 5 java api design-patterns method-chaining

我想在 Java 中调用一系列 API 调用。要求是在后续的 API 调用请求中会用到一些 API 的响应。我可以使用某些循环来实现这一点。但我想以实现通用的方式使用设计模式。有什么帮助吗?

责任链不能满足我的需要,因为一开始我不知道我的请求上下文是什么。

String out = null;
Response res = execute(req);
out += res.getOut();
req.setXYZ(res.getXYZ);
Response res = execute(req);
out += res.getOut();
req.setABC(res.getABC);
Response res = execute(req);
out += res.getOut();

System.out.println("Final response::"+out);
Run Code Online (Sandbox Code Playgroud)

goo*_*ump 0

感谢大家的意见,最后我找到了一个满足我需求的解决方案。我使用一个 Singleton 来执行请求。对于每种类型的命令,都会有一组以特定顺序执行的请求。每个命令都有特定的请求执行顺序,我将其存储在具有请求唯一 ID 的数组中。然后将数组保存在针对命令名称的映射中。

在循环中,我运行数组并执行,每次迭代后,我不断将响应设置回请求对象,并最终准备输出响应。

    private static Map<RequestAction,String[]> actionMap = new HashMap<RequestAction, String[]>();

    static{
    actionMap.put(RequestAction.COMMAND1,new String[]{WebServiceConstants.ONE,WebServiceConstants.TWO,WebServiceConstants.FOUR,WebServiceConstants.THREE});
    actionMap.put(RequestAction.THREE,new String[]{WebServiceConstants.FIVE,WebServiceConstants.ONE,WebServiceConstants.TWO});}


    public Map<String,Object> execute(ServiceParam param) {

    String[] requestChain = getRequestChain(param);

    Map<String,Object> responseMap = new HashMap<String, Object>();


    for(String reqId : requestChain) {

        prepareForProcessing(param, tempMap,responseMap);

        param.getRequest().setReqId(reqId);

        //processing the request
        tempMap = Service.INSTANCE.process(param);

        //prepare responseMap using tempMap         

        param.setResponse(response);

    }

    return responseMap;
}
Run Code Online (Sandbox Code Playgroud)