二.遇到多个构造器参数时要考虑使用构建器

1.静态工厂和构造器有个共同的局限性:他们都不能很好地扩展到大量的可选参数。
2.javabean模式弥补了这一缺点,但是它自身也有严重的缺点,构造过程中javabean可能处于不一致的状态,javaBeans模式使得把类做成不可变的可能性不复存在
3.当可选参数过多时,使用构建器—建造者模式的一种形式

import java.io.Serializable;

/**
 * @Author pao
 * @Date 2021/2/21 17:33
 * @Description
 */
public class Person implements Serializable {

    private String name;
    private String age;
    private String sex;
    private String country;
    private String edc;

    private Person(Builder builder) {
        this.name = builder.name;
        this.age = builder.age;
        this.sex = builder.sex;
        this.country = builder.country;
        this.edc = builder.edc;
    }


    public static class Builder{


        private String name;
        private String age;
        private String sex;
        private String country;
        private String edc;

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

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

        public Builder setSex(String sex) {
            this.sex = sex;
            return this;
        }

        public Builder setCountry(String country) {
            this.country = country;
            return this;
        }

        public Builder setEdc(String edc) {
            this.edc = edc;
            return this;
        }


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

测试:

public class Test {


    public static void main(String[] args) {

        Person build = new Person.Builder().setAge("10").build();

        System.out.println(build.toString());

    }
}

版权声明:本文为paotaiaaaaaa原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。