java 建造者模式

package de.bvb.test3;

/**
 * 建造者模式: 假如一个类有4个字段,每个字段或者每几个字段的组合都需要设置为构造函数,构造函数就比较麻烦
 * 而且如果再加一个字段进去也不好拓展.
 * 就需要使用到建造者模式了
 * 
 * 实例: android中的dialog, okHttp以及Retrofit 
 * 
 * 调用代码:
 * Person p1 = new Person.Builder().setId("0").setName("name").build();
 * Person p2 = new Person.Builder().setSalary(11).build();
 *
 */
public class Person {
    private String id;
    private String name;
    private int age;
    private double salary;

    public Person(Builder builder) {
        this.id = builder.id;
        this.name = builder.name;
        this.age = builder.age;
        this.salary = builder.salary;
    }

    public static class Builder {
        private String id;
        private String name;
        private int age;
        private double salary;

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

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

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

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

        public Builder setSalary(double salary) {
            this.salary = salary;
            return this;
        }
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

}

 

posted @ 2017-01-04 14:43  MarcoReus  阅读(145)  评论(0编辑  收藏  举报