Builder构建模式

声明:个人笔记,无参考学习价值
个人理解:
1.构建一个复杂对象
2.对外只提供传参的入口,并隐藏内部实现
3.外部无法修改内部实现
几个知识点:
1.私有化Person的构造参数,外部无法调用
2.创建一个静态内部类Builder作为与外界交互的口
3.通过链式调用,方法的返回值 return this,就是自己
4.最后创建一个build()方法,return Person类的构造方法,将Builder传到Person中,此时Builder这个类中已经装载了外界传递的数据,通过Person的构造方法,数据就传到了Person类中,可以构造代码功能了
示例代码:

package com.myself.learningdemo;

public class Person {

    private String name;
    private String sex;
    private String job;
    private int age;
    private Person(Builder builder) {
       this.age =  builder.age;
       this.name = builder.name;
       this.sex = builder.sex;
       this.job = builder.job;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", job='" + job + '\'' +
                ", age=" + age +
                '}';
    }

    static class Builder {
        private String name;
        private String sex;
        private String job;
        private int age;
        public Builder name(String name) {
            this.name = name;
            return this;
        }
        public Builder age(int age) {
            this.age = age;
            return this;
        }
        public Builder sex(String sex) {
            this.sex = sex;
            return this;
        }
        public Builder job(String job) {
            this.job = job;
            return this;
        }
        public Person build() {
            return new Person(this);
        }
    }
}

//外部调用
Person person = new Person.Builder()
                                              .age(1)
                                              .name("haha")
                                               .job("worker")
                                                .sex("man")
                                                .build();
person.toString();

你可能感兴趣的:(Builder构建模式)