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

来源:互联网 发布:怎么绑定淘宝银行卡 编辑:程序博客网 时间:2024/05/22 01:26
可以采用重叠构造器的方式,参数由少到多。但是最后,会出现一个参数极多的构造函数。在包含多个参数的构造函数中,会显得很晦涩,参数顺序极易搞乱,导致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
原创粉丝点击