前言
看到《Effective Java》第2条:遇到多个构造器参数时要考虑用构建器。马上想起之前自己写的一段代码:
return InvestorPurchaseCurrentParamPackage.create(
investorSum.getReference_id(),
entityCode,
BigDecimal.valueOf(tradingRecord.getAmount()),
BigDecimal.valueOf(profit));
}
这段代码自己第一次review的时候也有点忘了,第一次参数是什么意思,第二个参数还算明白,第三个,第四个参数从字面上好像是amount 和 profit 吧。
这样其实问题就来了,可读性不好。
Builder模式就是用来解决这个问题:Builder模式能让创建多个参数的时候,可读性还是很强的。
改造
先看改造之后的代码,改造后的创建语句变为
return new InvestorPurchaseCurrentParamPackage.Builder()
.platformCode(investorSum.getReference_id())
.investorEntityCode(tradingRecord.getTradingUser())
.amount(tradingRecord.getAmount())
.profit(profit)
.build();
可以看到,可读性强了很多,platformCode,investorEntityCode,amount,profit 这些名称都是随便你定。
方法
public class InvestorPurchaseCurrentParamPackage extends AbstractInvestorPurchaseProductsParamPackage {
public InvestorPurchaseCurrentParamPackage(Builder builder){
super.platformCode = builder.platformCode;
super.entityCode = builder.investorEntityCode;
super.amount = builder.amount;
super.profit = builder.profit;
}
public static class Builder{
private String platformCode;
private String investorEntityCode;
private BigDecimal amount;
private BigDecimal profit;
public Builder platformCode(String platformCode){
this.platformCode = platformCode;
return this;
}
public Builder investorEntityCode(String investorEntityCode){
this.investorEntityCode = investorEntityCode;
return this;
}
public Builder amount(BigDecimal amount){
this.amount = amount;
return this;
}
public Builder profit(BigDecimal profit){
this.profit = profit;
return this;
}
public InvestorPurchaseCurrentParamPackage build(){
return new InvestorPurchaseCurrentParamPackage(this);
}
}
}
可以看到,逻辑是这样的:
定义一个 static 类型的 内部类 Builder,并且Builder类内部的属性就是我们要赋值的属性 —> 通过各个方法把我们要赋的值封装到 Builder的对象中,返回 this,这样就可以使用链式的结构 —> 最后定义一个 build() 方法,创建目标对象,并且传入已经封装了各个参数的 Builder 对象。 —> 目标对象定义一个参数为Builder对象的构造函数 —> 赋值 完成创建目标对象。
这样就是一个Builder模式的实现思路。当有多个参数的时候用这个模式蛮好的。
That’s it.
1756

被折叠的 条评论
为什么被折叠?



