文章目录
建造者模式
可以在不同的构建过程中使用相同的建造者。
builder 链式调用创建对象就是建造者模式的使用
示例代码
java
public class Human {
private int age;
private String name;
private int sex;
@Override
public String toString() {
return "Human{" +
"age=" + age +
", name='" + name + '\'' +
", sex=" + sex +
'}';
}
public static void main(String[] args) {
Human wangshilei = HumanBuilder.aHuman().withName("wangshilei").withAge(100).withSex(1).build();
System.out.println(wangshilei);
}
public static final class HumanBuilder {
private int age;
private String name;
private int sex;
private HumanBuilder() {
}
public static HumanBuilder aHuman() {
return new HumanBuilder();
}
public HumanBuilder withAge(int age) {
this.age = age;
return this;
}
public HumanBuilder withName(String name) {
this.name = name;
return this;
}
public HumanBuilder withSex(int sex) {
this.sex = sex;
return this;
}
public Human build() {
Human human = new Human();
human.age = this.age;
human.sex = this.sex;
human.name = this.name;
return human;
}
}
}
//输出 Human{age=100, name='wangshilei', sex=1}
如上 就是实际的使用
构建复杂对象的时候使用 提高代码的可读性
我们可以隐藏构造细节。给外部提供简单的接口就能构建对象