如何在Java中为一系列API调用构建自定义中间操作管道?

问题描述 投票:3回答:1

我正在开发一个项目,该项目提供要在实体上完成的操作列表,每个操作都是对后端的API调用。假设实体是一个文件,操作是转换,编辑,复制。有一些更简单的方法可以做到这一点,但我感兴趣的是一种允许我链接这些操作的方法,类似于java Streams中的中间操作,然后当我点击终端操作时,它决定执行哪个API调用,以及执行可能需要的任何优化。我的API调用取决于其他操作的结果。我在考虑创建一个界面

interface operation{

operation copy(Params ..);  //intermediate

operation convert(Params ..);  // intermediate

operation edit(Params ..); // intermediate

finalresult execute(); // terminal op

}

现在,这些函数中的每一个都可能会根据创建管道的顺序影响另一个函数。我的高级方法是将操作名称和params保存在操作方法的各个实现中,并使用它来决定和优化execute方法中我想要的任何内容。我觉得这是一个不好的做法,因为我在操作方法中没有任何技术,这感觉更像是一个构建器模式,而不是那样。我想知道我的方法的想法。在java中有没有更好的设计来构建操作管道?

抱歉,如果这个问题看起来模糊不清,但我基本上是在寻找一种在java中构建操作管道的方法,同时我会对我的方法进行审核。

java design-patterns functional-programming stream
1个回答
1
投票

你应该看一下像这样的模式

EntityHandler.of(remoteApi, entity)
             .copy()
             .convert(...)
             .get();

public class EntityHandler {
    private final CurrentResult result = new CurrentResult();
    private final RemoteApi remoteApi;

    private EntityHandler(
          final RemoteApi remoteApi,
          final Entity entity) {
       this.remoteApi = remoteApi;
       this.result.setEntity(entity);
    }

    public EntityHandler copy() {
       this.result.setEntity(new Entity(entity)); // Copy constructor
       return this;
    }

    public EntityHandler convert(final EntityType type) {
       if (this.result.isErrored()) {
          throw new InvalidEntityException("...");
       }

       if (type == EntityType.PRIMARY) {
          this.result.setEntity(remoteApi.convertToSecondary(entity));
       } else {
          ...
       }

       return this:
    }

    public Entity get() {
       return result.getEntity();
    }

    public static EntityHandler of(
          final RemoteApi remoteApi, 
          final Entity entity) {
       return new EntityHandler(remoteApi, entity);
    }
}

关键是保持状态不可变,并在本地化的地方处理线程安全,例如在CurrentResult中。

© www.soinside.com 2019 - 2024. All rights reserved.