[EJ读书笔记]第2条:遇到多个构造器参数时要考虑用构建器

可以采用重叠构造器的方式,参数由少到多。但是最后,会出现一个参数极多的构造函数。在包含多个参数的构造函数中,会显得很晦涩,参数顺序极易搞乱,导致debug指数极高的错误。
如:
public Student(int age, int hight, int weight, String nation, String name) {
    super();
    this.age = age;
    this.hight = hight;
    this.weight = weight;
    this.nation = nation;
    this.name = name;
} 

如果你要这么调用

Student(16,166,150,"han","han");

我觉得,这个166和150传反了,你也很难发现吧,特别是写到天昏地暗的时候。
你也可以采用java bean的方式,getters&setters方法搞好,直接生成一个空构造器的实例。然后填进去。
但是,java bean的模式有一个问题,那就是,因为是分段构造的,在构造的过程中,这个java bean可能同时被修改,会造成数据不一致的问题。这是线程上的危险。
最好的解决办法,就是使用构建器,也就是builder。

public class Example{
    private final int age;
    private final int hight;
    private final int weight;
    private final String nation;
    private final String name;

    public static class Builder {
        /* required parameters */
        private final int age;
        private final String name;

        /* optional parameters */
        private int weight;
        private String nation;  
        private int hight;

        public Builder(int age, String name){
            this.age = age;
            this.name = name;       
        }

        public Builder nation(String nation) {
            this.nation = nation;
            return this;
        }

        public Builder weight(int weight) {
            this.weight= weight;
            return this;
        }

        public Builder hight(int hight) {
            this.hight= hight;
            return this;
        }

        public Example build() {
            return new Example(this);
        }
    }

    private Example(Builder builder) {
        this.age = builder.age;
        this.hight = builder.hight;
        this.weight = builder.weight;
        this.nation = builder.nation;
        this.name = builder.name;
    }
}

ps:
在抽象工厂中调用newInstance方法来充当build方法的一部分,这种模式隐藏这许多问题。newInstance方法总是企图调用类的无参构造器,但是这个构造器或许根本不存在。会抛出InstantiationException或者IllegalAccessException,这样既不优雅,还会传播异常。不过builder模式弥补了这个缺陷。
这个故事告诉我们,自己写代码的时候,特别是在基于框架写model的时候,一定要记得给个无参的构造函数。

Builder模式代码冗长,所以并不建议处处使用。如果类的构造器或者静态工厂中具有多个参数,设计者种类时,Builder模式就是不错的选择。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值