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

标签 java 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(),其中 BuilderProblem 的嵌套类,或者 Problem.builder() (无 new),其中 builder() 是返回 Problem.Builder 的静态方法。

关于java - 拆分 Java 构建器以避免多次编写相同的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42870668/

相关文章:

java - 自定义 Java 查询类 (DSL) : Builder pattern, 静态导入或其他用于复杂查询的东西?

xml - Ruby XML::Builder 元素名称中带有连字符

java - hashmap中迭代器和for循环的区别

java - 设置值后 SharedPreferences 返回默认值

java - 八皇后数组越界 (Java)

java - 在 JeroMQ 中将文件作为消息发送

Flash Builder 4.7 商业应用程序 - 无设计 View

java - android测试-EditText即使有字符也返回空

android - 用 list<> 填充 builder.setItem

ruby-on-rails - Rails 3 - XML 生成器