Setters AND(不是 OR 或 VS)构建器模式

2024-01-28

我遇到过一种情况,我使用构建器模式来构造对象。最好的例子是披萨代码

public class Pizza {
  private int size;
  private boolean cheese;
  private boolean pepperoni;
  private boolean bacon;

  public static class Builder {
    //required
    private final int size;

    //optional
    private boolean cheese = false;
    private boolean pepperoni = false;
    private boolean bacon = false;

    public Builder(int size) {
      this.size = size;
    }

    public Builder cheese(boolean value) {
      cheese = value;
      return this;
    }

    public Builder pepperoni(boolean value) {
      pepperoni = value;
      return this;
    }

    public Builder bacon(boolean value) {
      bacon = value;
      return this;
    }

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

  private Pizza(Builder builder) {
    size = builder.size;
    cheese = builder.cheese;
    pepperoni = builder.pepperoni;
    bacon = builder.bacon;
  }
}

到目前为止,一切都很好。

现在让我们假设一个我需要的用例update the cheese。那需要一个setter。我从未见过构建器模式与设置器共存的例子,这让我怀疑我所做的是反模式。

setter 和 builder 可以共存吗?


您从未见过它的使用,因为大多数时候,构建器模式用于构建不可变的对象。

但我不明白为什么他们不能共存。构建器构建一个对象,并且你希望构建的对象是可变的,那么它可以有setter。但是,如果它是可变的并且具有设置器,为什么不使用简单的构造函数构建对象,并调用设置器来更改状态呢?该构建器不再真正有用,除非许多字段中只有一两个字段是可变的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Setters AND(不是 OR 或 VS)构建器模式 的相关文章

随机推荐