首页 > 解决方案 > Java - 我可以在 Builder 方法中添加业务逻辑吗?

问题描述

我目前正在重构我们的 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);
    }
  }
}

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

标签: javabuilderbusiness-logic

解决方案


推荐阅读