Builder模式构建器
当类中参数较多,且并非所有参数都必须设置时使用
优势:builder可以有多个可变参数;因为builder利用单独的方法来设置每个参数,你想要多少个可变参数,它们就可以有多少个
class Dog {
private String name;
private int age;
private char sex;
private Dog(Builder builder) {
this.name = builder.name;
this.age = builder.age;
this.sex = builder.sex;
}
public static class Builder {
private String name;
private int age;
private char sex;
public Builder(String name) {
this.name = name;
}
public Builder age(int age) {
this.age = age;
return this;
}
public Builder sex(char sex) {
this.sex = sex;
return this;
}
public Dog build() {
return new Dog(this);
}
}
@Override
public String toString() {
return "Dog [name=" + name + ", age=" + age + ", sex=" + sex + "]";
}
}
public class Demo {
public static void main(String[] args) {
Dog d = new Dog.Builder("姓名").age(10).sex('q').build(); //参数可以随意定义,顺序不限,个数不限
System.out.println(d);
}
}