使用Builder模式进行美化代码

来源:互联网 发布:mac os 10.11.6 镜像 编辑:程序博客网 时间:2024/06/10 01:40

在很多情况下我们需要定义一个Class且里面有很多成员变量的时候通常我们的写法是

class Person {    private String name;    private int age;    private int sex;    private int high;    private int face;    private int weight;    private int foot;    public Person() {...}    public Person(String name) {...}    ...    public Person(String name, int age, int sex, int high, int face, int weight, int foot) {    }    }

我们为了不让一个构造函数过长,所以我们提供了很多个构造函数所以我们new出一个对象的时候看起来不是很直观。

Person p = new Person();p.setName();p.setAge();...p.setWeight();

当然我们还有以上这种方式,JavaBean这种方式是可以 当时有时候感觉代码太多行了。
所以就有了Builder模式来专门针对这种成员变量过多的类进行new使用,大概定义如下:

class Person {    private String name;    private int age;    private int sex;    private int high;    private int face;    private int weight;    private int foot;    public Person(Builder builder) {        name = builder.name;        age = builder.age;        sex = builder.sex;        high = builder.high;        face = builder.face;        weight = builder.weight;        foot = builder.foot;    }    public static class Builder {        private String name;        private int age;        private int sex;        private int high;        private int face;        private int weight;        private int foot;        public Person build() {            return new Person(this);        }        public Builder setName(String name) {            this.name = name;            return this;        }        public Builder setAge(int age) {            this.age = age;            return this;        }        public Builder setSex(int sex) {            this.sex = sex;            return this;        }        public Builder setHigh(int high) {            this.high = high;            return this;        }        public Builder setFace(int face) {            this.face = face;            return this;        }        public Builder setWeight(int weight) {            this.weight = weight;            return this;        }        public Builder setFoot(int foot) {            this.foot = foot;            return this;        }    }}

然后我们在Demo测试中只要这么写

Person p = new Person.Builder().setAge(12).setFace(12).setFoot(12).setHigh(180).setName("jayu").setSex(1).setWeight(89).build();

是不是看起来清爽多了,以后多成员变量的就使用了这种方式来写更有逼格,不是么。

1 0
原创粉丝点击