码迷,mamicode.com
首页 > 其他好文 > 详细

使用Builder模式进行美化代码

时间:2015-05-08 23:58:32      阅读:284      评论:0      收藏:0      [点我收藏+]

标签:模式

在很多情况下我们需要定义一个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();

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

使用Builder模式进行美化代码

标签:模式

原文地址:http://blog.csdn.net/neacy_zz/article/details/45586881

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!