- 建造者模式
- 意图:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
- 例子 :构建一个复杂的
Order对象,包含客户信息、商品列表、送货地址等,一步步清晰构造。
以下是一个建造者模式(Builder Pattern)的 Java 实现示例,模拟构建一个复杂的 Order 对象(包含客户信息、商品列表、送货地址等):
java
import java.util.ArrayList;
import java.util.List;
// 1. 定义最终要构建的复杂对象:Order
class Order {
private String customerName;
private String customerPhone;
private List<String> items;
private String shippingAddress;
// 私有构造方法,只能通过 Builder 构建
private Order(Builder builder) {
this.customerName = builder.customerName;
this.customerPhone = builder.customerPhone;
this.items = builder.items;
this.shippingAddress = builder.shippingAddress;
}
// 提供访问方法
public String getCustomerName() {
return customerName;
}
public String getCustomerPhone() {
return customerPhone;
}
public List<String> getItems() {
return items;
}
public String getShippingAddress() {
return shippingAddress;
}
@Override
public String toString() {
return "Order{" +
"customerName='" + customerName + '\'' +
", customerPhone='" + customerPhone + '\'' +
", items=" + items +
", shippingAddress='" + shippingAddress + '\'' +
'}';
}
// 2. 定义建造者类(Builder)
public static class Builder {
private String customerName;
private String customerPhone;
private List<String> items = new ArrayList<>();
private String shippingAddress;
// 设置客户信息
public Builder withCustomer(String name, String phone) {
this.customerName = name;
this.customerPhone = phone;
return this;
}
// 添加商品
public Builder addItem(String item) {
this.items.add(item);
return this;
}
// 设置送货地址
public Builder withShippingAddress(String address) {
this.shippingAddress = address;
return this;
}
// 构建 Order 对象
public Order build() {
// 可以在此处添加校验逻辑
if (customerName == null || customerPhone == null) {
throw new IllegalStateException("客户信息不完整");
}
if (items.isEmpty()) {
throw new IllegalStateException("商品列表不能为空");
}
return new Order(this);
}
}
}
// 3. 客户端代码
public class BuilderPatternDemo {
public static void main(String[] args) {
// 使用建造者逐步构建 Order 对象
Order order = new Order.Builder()
.withCustomer("张三", "13800138000")
.addItem("商品A")
.addItem("商品B")
.withShippingAddress("北京市海淀区")
.build();
// 输出订单信息
System.out.println(order);
}
}