模式介绍

建造者模式是一种创建型设计模式,它允许您分步骤创建复杂对象。该模式特别适用于当一个对象需要经过多个步骤才能创建完成时。建造者模式将对象的构建与表示分离,使得同样的构建过程可以创建不同的表示。

使用场景

  • 当创建复杂对象的算法应该独立于该对象的组成部分以及它们的装配方式时
  • 当构造过程必须允许被构造的对象有不同的表示时
  • 当需要生成的对象具有复杂的内部结构时

代码示例

public class Computer {
    private String cpu;
    private String ram;
    private String storage;

    private Computer(ComputerBuilder builder) {
        this.cpu = builder.cpu;
        this.ram = builder.ram;
        this.storage = builder.storage;
    }

    public static class ComputerBuilder {
        private String cpu;
        private String ram;
        private String storage;

        public ComputerBuilder setCpu(String cpu) {
            this.cpu = cpu;
            return this;
        }

        public ComputerBuilder setRam(String ram) {
            this.ram = ram;
            return this;
        }

        public ComputerBuilder setStorage(String storage) {
            this.storage = storage;
            return this;
        }

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

优缺点

优点

  • 可以更精细地控制产品的创建过程
  • 将复杂对象的创建步骤分解在不同的方法中
  • 隔离了复杂对象的创建和使用

缺点

  • 产品必须有共同点,范围有限制
  • 如内部变化复杂,会有很多的建造类
  • 建造者模式所创建的产品一般具有较多的共同点