建造者模式(Builder)用以*构建对象,主要功能就是代替对象的构造函数,更加*化。
案例:
/**
* @author Gjing
**/
class Custom {
private Integer age;
private String name;
private String address;
static Custom.Builder builder(){
return new Custom.Builder();
}
private Custom(Builder builder) {
this.age = builder.age;
this.name = builder.name;
this.address = builder.address;
}
@Override
public String toString() {
return "Custom{" +
"age=" + age +
", name='" + name + '\'' +
", address='" + address + '\'' +
'}';
}
public static class Builder {
private Integer age;
private String name;
private String address;
Builder() {
}
Builder age(Integer age) {
this.age = age;
return this;
}
Builder name(String name) {
this.name = name;
return this;
}
Builder address(String address) {
this.address = address;
return this;
}
Custom build() {
return new Custom(this);
}
}
}
使用:
/**
* @author Gjing
**/
public class Test {
public static void main(String[] args) {
Custom custom = Custom.builder().age(11).address("厦门市").build();
System.out.println(custom.toString());
}
}
以上为个人理解,有错误的地方欢迎各位指正