Builder 优雅的链式调用来实现实例化对象
1. 首先在实体类中,构造一个内部类,由内部类来完成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插件实现,减少人工写代码的工作量
标签:java,String,habit,Builder,private,Person,实例,public
来源: https://www.cnblogs.com/guanbin-529/p/10927225.html