gpt4 book ai didi

Java 对象的部分构造

转载 作者:行者123 更新时间:2023-12-02 10:42:29 24 4
gpt4 key购买 nike

我有一个复杂的对象,它由几个部分组成。每个部分都需要从不同的服务(REST 调用)获取数据。

public class Resource {
int quantity; // Service 1
String name; // Service 2
Price price; // Service 2, 3
...
}

public class Price {
double value; // Service 2
String currency; // Service 2
int discount_percentage; // Service 3
}

我计划使用 AbstractFactories 和 Java 的 CompletableFuture 来完成同样的任务。

但是,我不确定如何才能做到这一点 - 有什么建议吗?

最佳答案

下面的示例使用构建器和 CompletableFuture 而不是 AbstractFactory,但也许有帮助

public class Test {

public static void main(String... args) {
CompletableFuture<ComplexObject> completableFuture = CompletableFuture
.supplyAsync(()-> ComplexObject.builder())
.thenApply(cob -> cob.withComplexProp1(restService1.getDetails()))
.thenApply(cob -> cob.withComplexProp2(restService2.getDetails()))
.thenApply(cob -> cob.withComplexPropN(restServiceN.getDetails()))
.thenApply(cob -> cob.build());
try {
ComplexObject co = completableFuture.get();
} catch (Exception e) {
System.err.println("could not build the complex object");
}
}


}


class ComplexObject {
private Object complexProp1;
private Object complexProp2;
private Object complexPropN;

private ComplexObject() {}

public static ComplexObjectBuilder builder() {
return new ComplexObjectBuilder();
}

public static class ComplexObjectBuilder {

private Object complexProp1;
private Object complexProp2;
private Object complexPropN;

private ComplexObjectBuilder() {

}

public ComplexObjectBuilder withComplexProp1(Object complexProp1) {
// process the received complexProp1 before setting it into the builder
this.complexProp1 = complexProp1;
return this;
}
public ComplexObjectBuilder withComplexProp2(Object complexProp1) {
// process the received complexProp2 before setting it into the builder
this.complexProp2 = complexProp2;
return this;
}
public ComplexObjectBuilder withComplexPropN(Object complexProp1) {
// process the received complexPropN before setting it into the builder
this.complexPropN = complexPropN;
return this;
}

public ComplexObject build() {
ComplexObject co = new ComplexObject();
co.complexProp1 = this.complexProp1;
co.complexProp2 = this.complexProp2;
co.complexPropN = this.complexPropN;
return co;
}
}
}

关于Java 对象的部分构造,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52833598/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com