设计模式:Builder模式(多个构造器参数时可显著改善可读性)

前言


看到《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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值