zoukankan      html  css  js  c++  java
  • java

    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插件实现,减少人工写代码的工作量

  • 相关阅读:
    leetcode 21 Merge Two Sorted Lists
    leetcode 20 Valid Parentheses
    leetcode 19 Remove Nth Node From End of List
    [学习笔记]守护进程深入理解
    [学习笔记]父进程wait和waitpid
    [学习笔记]进程终止的5种方式
    [学习笔记]父子进程共享文件描述符理解
    [学习笔记]Vfork深入理解
    [学习笔记]_exit和exit深入理解
    [学习笔记]孤儿进程僵死进程
  • 原文地址:https://www.cnblogs.com/guanbin-529/p/10927225.html
Copyright © 2011-2022 走看看