gpt4 book ai didi

java - 哪种设计模式最适合避免方法中的多个参数

转载 作者:行者123 更新时间:2023-12-01 18:42:34 27 4
gpt4 key购买 nike

我有以下类(class):

public class SomeAssebler {

private EnrichedRequest assembleBasicEnrichedRequest(BasicRequest request) {
EnrichedRequest enrichedRequest = new EnrichedRequest();
if (request != null) {
enrichedRequest.setId(request.getId());
enrichedRequest.setDate(request.getDate());
enrichedRequest.setParam(request.getParam());
}
return enrichedRequest;
}

private static EnrichedRequest assembleGeoDataEnrichedRequest(EnrichedRequest request, GeoData geoData) {
EnrichedRequest geoEnrichedRequest = Optional.ofNullable(request).orElse(new EnrichedRequest());
if (geoData != null) {
geoEnrichedRequest.setCity(geoData.getCity());
geoEnrichedRequest.setCountryCode(geoData.getCountryCode());
}
return geoEnrichedRequest;
}

private static EnrichedRequest assembleUserAgentEnrichedRequest(EnrichedRequest request, UserAgentData userAgentData) {
EnrichedRequest userAgentEnrichedRequest = Optional.ofNullable(request).orElse(new EnrichedRequest());
if (userAgentData != null) {
userAgentEnrichedRequest.setBrowser(userAgentData.getBrowserCode());
userAgentEnrichedRequest.setOperatingSystem(userAgentData.getOsCode());
userAgentEnrichedRequest.setManufacturer(userAgentData.getBrand());
}
}

public static EnrichedRequest assembleEnrichedRequest(BasicRequest request, GeoData geoData, UserAgentData userAgentData) {
EnrichedRequest enrichedRequest = assembleBasicEnrichedRequest(request);
enrichedRequest = assembleGeoDataEnrichedRequest(enrichedRequest, geoData);
enrichedRequest = assembleUserAgentEnrichedRequest(enrichedRequest, userAgentData);
return enrichedRequest;
}
}

然后在不同的变压器中调用它:在地理数据转换器中

new KeyValue<>(key, assembleEnrichedRequest(basicRequest, geoData, null))

在 UserAgentTransformer 中:

new KeyValue<>(key, assembleEnrichedRequest(enrichedRequest, null, userAgent))

如果将来添加更多“丰富器”,这可能会变得非常难看。有人知道我如何才能更好地设计这个吗?我想到了 Builder 设计模式,但我不确定。

最佳答案

您可以使用Builder Pattern,但您必须对代码进行一些更改。

你可以从这个link查看它解释了如何使用构建器模式及其解决的问题。您可以尝试类似的方法,有很多不同的方法来创建 Builder 类。

public static class EnrichedRequestBuilder() {
private EnrichedRequest enrichedRequest:
private BasicRequest basicRequest:
private GeoData geoData;
private UserAgentData userAgentData;

public EnrichedRequestBuilder enrichedRequest(EnrichedRequest e) {
this.enrichedRequest = e;
return this;
}

public EnrichedRequestBuilder basicRequest(BasicRequest e) {
this.basicRequest = e;
return this;
}

public EnrichedRequestBuilder build() {
return new EnrichedRequestBuilder(this);
}


}

new EnrichedRequestBuilder().basicRequest(b).enrichedRequest(e).build();

关于java - 哪种设计模式最适合避免方法中的多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59895459/

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