【Design Pattern】Creational - Builder

Posted by 西维蜀黍 on 2018-11-11, Last Modified on 2025-07-22

When to Use It

  • When an object has many optional fields or configurations.
  • When object construction involves complex steps or validation.
  • When you want to avoid constructor telescoping (i.e., multiple constructors with different parameters).

定义

建造者模式(Builder Pattern)将一个复杂对象的构建与它的表示分离,使得同样的构建过程(但传入的参数不同)可以创建不同的表示。

构成

The Builder pattern typically involves:

  1. Product – the complex object being built.
  2. Builder – an interface or abstract class defining building steps.
  3. ConcreteBuilder – implements the Builder, maintaining the product.
  4. Director (optional) – controls the building sequence.

Java Example

public class House {
    private int rooms;
    private int floors;
    private boolean hasGarage;
    private boolean hasSwimmingPool;

    private House(Builder builder) {
        this.rooms = builder.rooms;
        this.floors = builder.floors;
        this.hasGarage = builder.hasGarage;
        this.hasSwimmingPool = builder.hasSwimmingPool;
    }

    public static class Builder {
        private int rooms;
        private int floors;
        private boolean hasGarage;
        private boolean hasSwimmingPool;

        public Builder rooms(int rooms) {
            this.rooms = rooms;
            return this;
        }

        public Builder floors(int floors) {
            this.floors = floors;
            return this;
        }

        public Builder hasGarage(boolean hasGarage) {
            this.hasGarage = hasGarage;
            return this;
        }

        public Builder hasSwimmingPool(boolean hasSwimmingPool) {
            this.hasSwimmingPool = hasSwimmingPool;
            return this;
        }

        public House build() {
            return new House(this);
        }
    }
}

// usage
House myHouse = new House.Builder()
    .rooms(4)
    .floors(2)
    .hasGarage(true)
    .hasSwimmingPool(false)
    .build();

Pros and Cons

✅ Pros

  • Readable and maintainable object construction.
  • Enforces immutability (if the product is immutable).
  • Great for objects with many optional or default fields.

❌ Cons

  • Can be verbose, especially if you implement your own builder manually.

分析

建造者模式过渡到模板方法模式

准备一个抽象类,将部分逻辑以具体方法以及具体构造函数的形式实现,然后声明一些抽象方法来迫使子类实现剩余的逻辑。

不同的子类可以以不同的方式实现这些抽象方法,从而对剩余的逻辑有不同的实现。这就是模板方法模式。

有意思的是,这个特殊的建造模式与模板方法有相似之处:construct()方法就相当于一个模板方法,这个方法调用其他的建造方法,如 buildPart1()、buildPart2()等基本方法。

因此,这使得此系统与模板方法模式相同。

建造者模式与工厂模式区别

我们可以看到,建造者模式与工厂模式是极为相似的,总体上,建造者模式仅仅只比工厂模式多了一个“导演类”的角色。在建造者模式的类图中,假如把这个导演类看做是最终调用的客户端,那么图中剩余的部分就可以看作是一个简单的工厂模式了。

与工厂模式相比,建造者模式一般用来创建更为复杂的对象,因为对象的创建过程更为复杂,因此将对象的创建过程独立出来组成一个新的类——导演类。也就是说,工厂模式是将对象的全部创建过程封装在工厂类中,由工厂类向客户端提供最终的产品;而建造者模式中,建造者类一般只提供产品类中各个组件的建造,而将具体建造过程交付给导演类。由导演类负责将各个组件按照特定的规则组建为产品,然后将组建好的产品交付给客户端。

Reference