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

时间:2018-08-17 00:52:42

标签: java builder business-logic

我目前正在重构Web应用程序中的代码,遇到一个非常复杂的对象,该对象需要由多个对象构建。复杂对象的每个属性都是通过执行某些逻辑得出的。我在网上搜索以找到一种干净的解决方案来重构此复杂对象的创建,并最终选择了Builder模式。下面是一个示例,说明了我的处理方法。

帐户对象

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);
    }
  }
}

这种方法正确吗?我从同事那里得到一些推论,即您不应在构建器方法中进行逻辑处理。我想知道我是否朝着正确的方向前进。任何帮助表示赞赏。谢谢。

0 个答案:

没有答案