引用: http://www.jianshu.com/p/1ddb69f1f67e 引用经典Builder/变种Builder模式及自动化生成代码插件
插件: http://blog.csdn.net/SoberChina/article/details/72953989?locationNum=2&fps=1
例子1:
使用 new Person.Builder().name("小猪").age("20").build();
1.Person类的构造函数是私有的。这样就不能直接实例化这个类
2.Person类是不可变的。里面的属性都是final的。只能在构造函数中初始化。然后提供了属性的get函数,可以去获取值。
public class Person {
private final String name; //变量都是final 只能在构造函数中初始化
private final String age;
private Person(Builder builder) {
name = builder.name;
age = builder.age;
}
public String getName() {
return name;
}
public String getAge() {
return age;
}
public static final class Builder {
private String name;
private String age;
public Builder() {
}
public Builder name(String val) {
name = val;
return this;
}
public Builder age(String val) {
age = val;
return this;
}
public Person build() {
return new Person(this);
}
}
}
例子2
使用 Person.newBuilder().name("小猪").age("20").build();
1、使用可以减少new,使用newBuilder()
2、有copy功能 newBuilder(Person copy)
/**
* Created by lch on 2017/10/26.
*/
public class Person {
private final String name; //变量都是final 只能在构造函数中初始化
private final String age;
private Person(Builder builder) {
name = builder.name;
age = builder.age;
}
public static Builder newBuilder() {
return new Builder();
}
public static Builder newBuilder(Person copy) {
Builder builder = new Builder();
builder.name = copy.name;
builder.age = copy.age;
return builder;
}
public String getName() {
return name;
}
public String getAge() {
return age;
}
public static final class Builder {
private String name;
private String age;
public Builder() {
}
public Builder name(String val) {
name = val;
return this;
}
public Builder age(String val) {
age = val;
return this;
}
public Person build() {
return new Person(this);
}
}
}
网友评论