简体   繁体   English

如何避免if语句并调用多个构造函数

[英]How to avoid if statement and call multiple constructors

I would like to ask how to handle with multiple constructors. 我想问一下如何处理多个构造函数。

if(a != null && b != null)
    return new QueryProducer(query, a, b);
else if(a != null)
    return new QueryProducer(query, a);
else if(b != null)
    return new QueryProducer(query, b);
else return new QueryProducer(query);

I would like to avoid complex if else blocks. 我想避免其他复杂的块。 Scalability is also not very good in this case. 在这种情况下,可伸缩性也不是很好。

How about using builder pattern here? 在这里使用构建器模式怎么样? See this link from Javacodegeeks for code example 请参阅Javacodegeeks的此链接以获取代码示例

QueryProducer.withQuery(yourQuery).withA(a).withB(b).build();

Create a builder that builds a QueryProducer based on the parameters passed. 创建一个构建器,该构建器根据传递的参数构建QueryProducer。 You can put all the logic for creating the object in one place. 您可以将创建对象的所有逻辑放在一个位置。 The other thing that comes to my mind is passing all three parameters to the constructor, and handling it there, but I almost always avoid putting any logic in the constructor because of the exceptions that can occur. 我想到的另一件事是将所有三个参数传递给构造函数,并在那里进行处理,但由于可能发生异常,我几乎总是避免在构造函数中放置任何逻辑。

As others have answered, if you have a situation in which any of the following are true, then you should strongly consider using the Builder Pattern (using a helper object -- usually defined by a static nested class in your object's class -- to construct the object you want): 正如其他人回答的那样,如果您遇到以下任何一种情况都成立的情况,那么您应该强烈考虑使用构建器模式(使用一个辅助对象,通常由对象类中的静态嵌套类定义)您想要的对象):

  • Do I have 4 or more parameters for my constructor? 我的构造函数是否有4个或更多参数?
  • Am I overloading constructors? 我是否在重载构造函数?
  • Does my constructor have parameters that specify data that is optional? 我的构造函数是否具有用于指定可选数据的参数?
  • Do I expect to add more parameters to my constructor at a future date? 我是否希望将来在我的构造函数中添加更多参数?
  • Do I want the readability of the JavaBean pattern while still being able to construct immutable objects? 我是否想要JavaBean模式的可读性,同时仍然能够构造不可变的对象?

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

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