1.概念
建造者模式(builder模式,属于创建型模式):通过将复杂对象的构建过程分解为多个步骤,使得对象的构建更加灵活和可控。
它适用于构建复杂对象,特别是当对象的构建过程涉及多个可选部分。
2.Demo
1.创建一个匿名内部类Builder,其属性与外部类的属性相同;
2.将外部类的构造方法私有化(private),使用内部类填充属性;
3.在外部类创建builder()方法;
4.在内部类创建builder()方法。
java
public class Student{
private int id;
private String name;
private int age;
// 1 构建匿名内部类, 属性与Student类属性一致
public static class Builder {
private int id;
private String name;
private int age;
public Builder id(int id) {
this.id = id;
return this;
}
public Builder name(String name) {
this.name = name;
return this;
}
public Builder age(int age) {
this.age = age;
return this;
}
// 4 最终构建返回
public Student build() {
return new Student(this);
}
}
// 2 创建静态builder方法,返回Builder类进行构造
public static Builder builder() {
return new Builder();
}
// 3 构造私有构造方法,将Builder中的属性进行赋值
private Student(Builder builder) {
this.id = builder.id;
this.name = builder.name;
this.age = builder.age;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
测试类:
java
public class Main {
public static void main(String[] args) {
Student student = Student.builder()
.id(1)
.age(12)
.name("李三")
.build();
System.out.println(student);
}
}
结果输出: