拆分 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
的嵌套 class,或 Problem.builder()
(没有 new
),其中 builder()
是 returns 一个 Problem.Builder
.
的静态方法
我有一段代码如下所示:
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
的嵌套 class,或 Problem.builder()
(没有 new
),其中 builder()
是 returns 一个 Problem.Builder
.