java - 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);
}
}
}
这种方法对吗?我从我的同事那里得到了一些反对意见,即您不应该在构建器方法中执行逻辑。我想知道我是否朝着正确的方向前进。任何帮助表示赞赏。谢谢你。
解决方案
推荐阅读
- azure-cosmosdb - 为什么获得 COUNT 个结果如此昂贵?
- delphi - 如何在“部署管理器”中编辑“本地路径”?
- python - Flask - 如何使用提供商特定的标头开发和调试 Azure Web App?
- python - 从三角形中生成随机点
- javascript - 如何为 JavaScript 中的数据条目动态列表创建删除项目图像按钮
- wordpress - Gravity Forms 能否与 CiviCRM 集成?
- mongodb - 比较 MongoDB 中的 2 个集合并将差异放在第 3 个
- list - 带有 NavigationLink 的 SwiftUI 列表。如何在点击时更改突出显示颜色?
- r - 如何在 R 中使用 lapply 消除异常
- c# - 将实例传递给 ASP.NET Core 依赖注入的缺点