建造者模式:Builder Pattern,将一个复杂对象的构建过程与它的表示分离,使得同样的构建过程可以创建不同的表示,属于创建型设计模式
建造者模式和工厂模式区别:
- 建造者模式:一般用于创建复杂对象
- 工厂模式:一般用于创建简单对象
简单实现:
public class BuilderDemo {
public static void main(String[] args) {
// 测试
Product product = Product.builder()
.setName("李四").setPrice(18).setSize(20)
.build();
System.out.println(product);
}
@Data
static class Product {
private String name;
private Integer price;
private Integer size;
public static Builder builder() {
// 返回一个构建器
return new Builder();
}
private Product(String name, Integer price, Integer size) {
this.name = name;
this.price = price;
this.size = size;
}
static class Builder {
private String name;
private Integer price;
private Integer size;
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setPrice(Integer price) {
this.price = price;
return this;
}
public Builder setSize(Integer size) {
this.size = size;
return this;
}
// 在调用builder时才会创建实例
public Product build() {
return new Product(name, price, size);
}
}
}
}