Java-我可以在生成器方法中添加业务逻辑吗?

Java-我可以在生成器方法中添加业务逻辑吗?,java,builder,business-logic,Java,Builder,Business Logic,我目前正在重构web应用程序中的代码,遇到了一个非常复杂的对象,需要从多个对象构建。复杂对象的每个属性都是通过执行一些逻辑派生的。我在网上搜索,以找到一个干净的解决方案来重构这个复杂对象的创建,并最终确定了构建器模式。下面是一个例子来说明我是如何做到这一点的 帐户对象 public class Account { private String accountNumber; private Boolean eligible; private Double balance; pub

我目前正在重构web应用程序中的代码,遇到了一个非常复杂的对象,需要从多个对象构建。复杂对象的每个属性都是通过执行一些逻辑派生的。我在网上搜索,以找到一个干净的解决方案来重构这个复杂对象的创建,并最终确定了构建器模式。下面是一个例子来说明我是如何做到这一点的

帐户对象

public class Account {
  private String accountNumber;
  private Boolean eligible;
  private Double balance;

  public Account(Account.Builder builder) {
    accountNumber = builder.accountNumber;
    eligible = builder.eligible;
    balance = builder.balance;
  }

  public String getAccountNumber() {
    return accountNumber;
  }

  public Boolean isEligible() {
    return eligible;
  }

  public Double getBalance() {
    return balance;
  }

  public static class Builder {
    private String accountNumber;
    private Boolean eligible;
    private Double balance;

    public static Builder builder() {
       return new Builder();
    }

    Builder withAccountNumber(String accountNumber) {
       this.accountNumber = accountNumber; // Simple assignment
       return this;
    }

    Builder withEligibility(Promotion promotion, CustomerType customerType) {
      // Run logic on the promotion and the type of customer to determine if the customer is eligible and then set the eligible attribute
       return this;
    }

    Builder withBalance(Promotion promotion, CustomerExpenses expenses) {
       // Run logic on the promotion and the customer expenses to determine the balance amount and set it to balance attribute
       return this;
    }

    Account build() {
       return new Account(this);
    }
  }
}

这种方法正确吗?我的同事们对我有些反感,认为你不应该在生成器方法中使用逻辑。我想知道我是否朝着正确的方向前进。感谢您的帮助。谢谢。

在我看来,with方法不应该包含基本转换之外的逻辑(与setter相同)。如果您希望在构建器中包含业务逻辑,那么它应该位于
build()
方法(或从中调用的私有方法)中。然后,逻辑将再次累积在单个方法中(在本例中为build()方法)。这就是现有代码中的情况。一种方法中的所有构建逻辑。我想通过重构来更好地组织它。有没有其他模式可以满足这个要求?首先。为什么要使用生成器模式?看起来更像是有一个简单的对象,业务逻辑污染了该对象的创建。我在上面代码中给出的对象就是一个例子。我试图构建的实际对象有168个属性,每个属性都有一些逻辑来派生它。我可以使用任何其他模式来帮助我以一种有意义的方式组织此代码。此外,我还查看了java api中的
StringBuilder
,它在构建
字符串所需的生成器方法中具有逻辑