多少个构造函数参数就太多了? [关闭]

2024-02-09

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

  • UserName
  • Email

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

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

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

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


需要考虑的两种设计方法

The essence http://www.hillside.net/plop/plop98/final_submissions/P10.pdf pattern

The 流畅的界面 https://martinfowler.com/bliki/FluentInterface.html pattern

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

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

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();
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

多少个构造函数参数就太多了? [关闭] 的相关文章

随机推荐