建造者模式
Builder — 分步骤构建复杂对象,把构建过程和表示分离
一句话理解
当一个对象的构造需要很多参数或多个步骤时,用建造者来一步步组装,而不是写一个超长的构造器。
解决什么问题
// 反面教材:参数太多,根本分不清每个参数是什么
new User("张三", 25, "北京", "13800138000", "test@mail.com", true, false, "admin");- 参数多了容易传错顺序
- 有些参数是可选的,要写大量重载构造器
- 代码可读性极差
怎么写
public class User {
private final String name;
private final int age;
private final String city;
private final String phone;
private final String email;
// 私有构造器,只能通过 Builder 创建
private User(Builder builder) {
this.name = builder.name;
this.age = builder.age;
this.city = builder.city;
this.phone = builder.phone;
this.email = builder.email;
}
// 静态内部类 Builder
public static class Builder {
// 必填
private final String name;
// 可选(给默认值)
private int age = 0;
private String city = "";
private String phone = "";
private String email = "";
public Builder(String name) {
this.name = name;
}
public Builder age(int age) { this.age = age; return this; }
public Builder city(String city) { this.city = city; return this; }
public Builder phone(String phone) { this.phone = phone; return this; }
public Builder email(String email) { this.email = email; return this; }
public User build() {
return new User(this);
}
}
}// 使用:链式调用,清晰易读
User user = new User.Builder("张三")
.age(25)
.city("北京")
.phone("13800138000")
.build();每个 setter 方法返回 this,形成链式调用(Method Chaining)。
前端中的建造者
// 链式构建 HTTP 请求
const response = await new RequestBuilder('/api/users')
.method('POST')
.header('Content-Type', 'application/json')
.body({ name: '张三' })
.timeout(5000)
.send()使用场景
- Lombok 的
@Builder注解 —— 自动生成 Builder 代码 StringBuilder/StringBuffer- OkHttp 的
Request.Builder - MyBatis 的
SqlSessionFactoryBuilder - 各种查询构建器(QueryBuilder)