我有一段代码,如下所示:
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
的静态方法。
关于java - 拆分 Java 构建器以避免多次编写相同的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42870668/