使用Builder代替多个重载的构造方法

package com.lujiatao;

public class Person {

    private String idCard;
    private String name;
    private boolean male;
    private String nation;

    public static class PersonBuilder {

        private String idCard;
        private String name = "匿名";
        private boolean male = true;
        private String nation = "汉";

        public PersonBuilder(String idCard) {
            this.idCard = idCard;
        }

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

        public PersonBuilder male(boolean male) {
            this.male = male;
            return this;
        }

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

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

    }

    private Person(PersonBuilder personBuilder) {
        idCard = personBuilder.idCard;
        name = personBuilder.name;
        male = personBuilder.male;
        nation = personBuilder.nation;
    }

    @Override
    public String toString() {
        return "Person{" +
                "idCard='" + idCard + '\'' +
                ", name='" + name + '\'' +
                ", male=" + male +
                ", nation='" + nation + '\'' +
                '}';
    }

}

你可能感兴趣的:(使用Builder代替多个重载的构造方法)