繁体   English   中英

拆分Java构建器以避免多次编写相同的代码

[英]Splitting the Java builder to avoid writing same code multiple times

我有一段代码如下所示:

Problem hashProblem;
String indexName;
if(condition.getOwner() != null) {
    indexName = sourceLocation ;
    hashProblem = new Problem().builder()
        .locationID(condition.getLocationID())
        .sourceLocation(condition.getSourceLocation())
        .build();
}
else {
    indexName = currentLocation;
    hashProblem = new Problem().builder()
        .locationID(condition.getLocationID())
        .currentLocation(criteria.getcurrentLocation())
        .build();
}

有没有办法以更优雅的方式编写此代码? 在构建hashProblem对象时,始终需要locationID。 我无法想出一种分割构建器的方法,这样我只能编写.locationID一次。 我正在使用Lombok( https://projectlombok.org/features/Builder.html )进行构建

当然。 构建器就像其他任何对象一样。 而不是创造的建设者和呼叫的build()在一个大的语句,可以保存到建设者的引用,做一些它有条件,然后调用build()

Problem hashProblem;
String indexName;
Builder builder = new Problem().builder().locationID(condition.getLocationID());
if(condition.getOwner() != null) {
    indexName = sourceLocation ;
    builder.sourceLocation(condition.getSourceLocation())
}
else {
    indexName = currentLocation;
    builder.currentLocation(criteria.getcurrentLocation())
}
hashProblem = builder.build();

顺便说一句, new Problem().builder()在命名约定方面看起来有点奇怪。 通常你会看到new Problem.Builder() ,其中Builder是一个嵌套的Problem类,或者是Problem.builder() (没有new ),其中builder()是一个返回Problem.Builder的静态方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM