gpt4 book ai didi

parameters - 多少个构造函数参数就太多了?

转载 作者:行者123 更新时间:2023-12-03 04:31:09 24 4
gpt4 key购买 nike

假设您有一个名为 Customer 的类,其中包含以下字段:

  • 用户名
  • 电子邮件
  • 名字
  • 姓氏

我们还可以说,根据您的业务逻辑,所有 Customer 对象都必须定义这四个属性。

现在,我们可以通过强制构造函数指定每个属性来轻松完成此操作。但是,当您被迫向 Customer 对象添加更多必填字段时,很容易看出这种情况会如何失控。

我见过一些类在其构造函数中接受 20 多个参数,但使用它们非常痛苦。但是,或者,如果您不需要这些字段,那么如果您依赖调用代码来指定这些属性,则可能会遇到未定义信息的风险,或更糟糕的是,会遇到对象引用错误。

有没有其他选择,或者您只需决定 X 数量的构造函数参数是否对您来说太多而无法忍受?

最佳答案

需要考虑的两种设计方法

essence图案

fluent interface图案

它们在意图上都很相似,因为我们慢慢地构建一个中间对象,然后一步创建我们的目标对象。

流畅界面的实际应用示例如下:

public class CustomerBuilder {
String surname;
String firstName;
String ssn;
public static CustomerBuilder customer() {
return new CustomerBuilder();
}
public CustomerBuilder withSurname(String surname) {
this.surname = surname;
return this;
}
public CustomerBuilder withFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public CustomerBuilder withSsn(String ssn) {
this.ssn = ssn;
return this;
}
// client doesn't get to instantiate Customer directly
public Customer build() {
return new Customer(this);
}
}

public class Customer {
private final String firstName;
private final String surname;
private final String ssn;

Customer(CustomerBuilder builder) {
if (builder.firstName == null) throw new NullPointerException("firstName");
if (builder.surname == null) throw new NullPointerException("surname");
if (builder.ssn == null) throw new NullPointerException("ssn");
this.firstName = builder.firstName;
this.surname = builder.surname;
this.ssn = builder.ssn;
}

public String getFirstName() { return firstName; }
public String getSurname() { return surname; }
public String getSsn() { return ssn; }
}
import static com.acme.CustomerBuilder.customer;

public class Client {
public void doSomething() {
Customer customer = customer()
.withSurname("Smith")
.withFirstName("Fred")
.withSsn("123XS1")
.build();
}
}

关于parameters - 多少个构造函数参数就太多了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40264/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com