2017-03-18 55 views
1

我有一段代码,它看起来象下面这样:分裂了Java生成器来避免写相同的代码多次

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。我正在使用龙目岛(https://projectlombok.org/features/Builder.html)作为建造者

回答

2

当然。建设者就像任何其他人一样是一个物体。除了创建构建器并在一个大声明中调用build(),您可以保存对构建器的引用,对其进行有条件的操作,然后致电build()

​​

顺便说一下,new Problem().builder()在命名约定方面看起来有点奇怪。通常您会看到new Problem.Builder(),其中Builder是嵌套类ProblemProblem.builder()(no new)其中builder()是一种返回Problem.Builder的静态方法。

+0

我忘了提及我正在使用龙目岛的建设者。如果我不使用新的Problem(),我会得到一个预期的错误方法调用 – user1692342

+0

如果我使用Lombok的Builder:Builder b = new Problem()。builder()。locationID(condition.getLocationID()); ,我得到一个错误Incompatible types – user1692342

+1

代替'Builder b',不管'Problem()。builder()'返回什么类型''''。我只是称它为'Builder',因为这是构建器类的通常名称。 –