在复杂对象的创建过程中,我们常常面临构造参数过多、构建步骤复杂、对象存在多种表示等挑战。生成器模式(Builder Pattern)通过将复杂对象的构建过程分离出来,使得相同的构建过程可以创建不同的表示。
生成器模式的核心结构
生成器模式包含四个关键角色:
- Product(产品):要创建的复杂对象
- Builder(生成器):抽象构建接口
- ConcreteBuilder(具体生成器):实现构建步骤
- Director(指挥者):控制构建过程(可选)
实战示例:数据库连接配置
// 产品类
public class DatabaseConfig {
private final String host;
private final int port;
private final String database;
private final String username;
private final String password;
private final int timeout;
private DatabaseConfig(Builder builder) {
this.host = builder.host;
this.port = builder.port;
this.database = builder.database;
this.username = builder.username;
this.password = builder.password;
this.timeout = builder.timeout;
}
// 生成器
public static class Builder {
private String host = "localhost";
private int port = 3306;
private String database;
private String username;
private String password;
private int timeout = 1000;
public Builder host(String host) {
this.host = host;
return this;
}
public Builder port(int port) {
this.port = port;
return this;
}
// 其他setter方法...
public DatabaseConfig build() {
if (database == null || username == null) {
throw new IllegalStateException("必需参数未设置");
}
return new DatabaseConfig(this);
}
}
}
// 使用示例
DatabaseConfig config = new DatabaseConfig.Builder()
.host("192.168.1.100")
.port(3306)
.database("test_db")
.username("admin")
.password("secret")
.timeout(5000)
.build();
模式优势与适用场景
优势:
- 构建过程清晰可控,参数设置灵活
- 避免过多的构造参数,提高代码可读性
- 可以构建不可变对象
- 链式调用优雅流畅
适用场景:
- 需要创建复杂对象且对象有多个组成部分
- 对象的构建过程需要不同的表示
- 需要创建不可变对象但参数较多
生成器模式在Lombok等工具中通过@Builder注解得到了极大简化,但其思想价值远高于实现本身。掌握生成器模式能够让你在复杂对象构建场景中游刃有余,写出更加清晰、灵活的代码。
947

被折叠的 条评论
为什么被折叠?



