使用参数化构造函数(带有必填字段)和设置器而不是使用构建器设计模式

Using Parameterized constructors(with mandatory fields) and setters instead of Using Builder Design Pattern

当我们有一个 class 有很多字段,其中一些是强制性的,一些是可选的,那么使用构造函数是一种不好的做法,因为有几个问题,一个是可读性差。 Builder Design Pattern 可能是我们分离构造逻辑并使用逐步方法创建对象的一种解决方案。 我的问题是:

1.) 为什么我们不能将 Setters 与包含强制字段而不是构建器模式的参数化构造函数结合使用?可以使用设置器设置可选字段。

2.) 为什么我们应该使用带有参数化构造函数的 Builder Design Pattern 而不是 Setters? 我能想到的原因之一是不变性。它还有哪些其他好处?

3.)如果我们不想要不变性,那么使用带参数化构造函数的 setter 而不是构建器模式是否合理?

1.) Why can't we use setters in combination with a parameterized constructor which will contain mandatory fields instead of Builder Pattern? The optional fields can be set using setters.

好吧,你可以做到这一点。但是考虑一下。

在构建器模式中,您进行一系列调用以设置参数,然后调用 build()build() 调用检查设置,然后创建、配置和初始化实例。

您可以执行与构造函数调用相同的操作,然后是一系列 setter 调用和一个 init 调用。然而:

  • class 之外的代码需要查看 setters 和 init 方法,并且它必须遵循“协议”。

  • class 中处理初始化等的代码需要更健壮。例如,如果一个实例在初始化之前被使用,或者如果一个概念上不可变的属性在初始化之后被改变,那么需要抛出异常。

2.) Why should we use the Builder Design Pattern over Setters with the parameterized constructor? One reason I could think of is Immutability. What other benefits does it have?

见上文。构建器模式是一种抽象构建协议的方式。它减少了不必要的耦合。

3.) If we don't want immutability, then is it justifiable to use setters with Parameterized constructors instead of the Builder Pattern?

是的。请参阅上面的理由。

当然,这种理由的强度取决于初始化协议的复杂程度,以及将其从使用 class.

的代码中抽象出来的好处有多大。