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插件实现,减少人工写代码的工作量
作者:guanbin —— 纵码万里千山
出处:https://www.cnblogs.com/guanbin-529/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。