Java--创建对象的可变参数过多时

/**
 * 创建对象时,对象可以有多个不同参数的构造方法。
 * 只采用构造方法时会造成构造方法过多,并且增加填参错误的概率。
 * 将可选参数用见名知意的方法来设置。
 *
 * @author orange
 */
public class Person {
    private String name;
    private int age;
    private String address;
    private String telNum;
    private boolean isMarriage;
    private String company;

    public static class Builder {
        //要求的必填参数,视情况而定,也可以没有哈
        private final String name;
        private final int age;

        //可选参数,可以设置不填写时的默认值
        private String address = "";
        private String telNum = "";
        private boolean isMarriage = false;
        private String company = "";

        //根据上面的必填参数。
        public Builder(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public Builder address(String val) {
            address = val;
            return this;
        }

        public Builder telNum(String val) {
            telNum = val;
            return this;
        }

        public Builder isMarriage(boolean val) {
            isMarriage = val;
            return this;
        }

        public Builder company(String val) {
            company = val;
            return this;
        }

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

    private Person(Builder builder) {
        this.name = builder.name;
        this.age = builder.age;
        this.address = builder.address;
        this.telNum = builder.telNum;
        this.isMarriage = builder.isMarriage;
        this.company = builder.company;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", address='" + address + '\'' +
                ", telNum='" + telNum + '\'' +
                ", isMarriage=" + isMarriage +
                ", company='" + company + '\'' +
                '}';
    }
}
Person person=new Person.Builder("orange",18).company("无名公司").build();
posted on 2021-11-19 10:37  15年的夏天  阅读(157)  评论(0)    收藏  举报