java - Builder模式实例化对象

Builder 优雅的链式调用来实现实例化对象

1.  首先在实体类中,构造一个Builder内部类,由Builder来完成Person的属性赋值,并最终执行build来完成Person的实例化

package com.example.entity;

/**
 * @author: GuanBin
 * @date: Created in 下午7:20 2019/5/26
 */
public class Person {
    private final String name;
    private String location;
    private String job;
    private String habit;

    private Person(Builder builder) {
        name = builder.name;
        location = builder.location;
        job = builder.job;
        habit = builder.habit;
    }


    public static final class Builder {
        private String name;
        private String location;
        private String job;
        private String habit;

        public Builder() {
        }

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

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

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

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

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

2.链式调用进行赋值

 

package com.example.java8test.bulider;

import com.example.entity.Person;

/**
 * @author: GuanBin
 * @date: Created in 下午7:30 2019/5/26
 */
public class BuliderTest {

    public static void main(String[] args) {

        Person person = new Person.Builder()
                .name("guanbin")
                .location("shanghai")
                .habit("football")
                .job("it")
                .build();


    }
}

3. 内部类的代码,可以由InnerBuilder插件实现,减少人工写代码的工作量

 

 

 

 

 

posted @ 2019-05-26 19:47  纵码万水千山  阅读(1223)  评论(0编辑  收藏  举报