异构项目集合的构建器模式

Builder Pattern for Collection of Heterogeneous Items

我正在尝试找出为异构项集合(在数据中,而不是类型中)设置构建器的正确方法。

假设我有一个我想要构建的钉板。钉板包含一个 Pegs 向量,每个向量都有一组坐标。钉子也有颜色,以及一系列其他 POD 属性。

我正在实施构建器模式来构建不同的 PegBoards 但我不确定如何处理以下问题:

基本上,我喜欢 Builder 模式构造对象的有条不紊的方式,但我也需要在构建过程中具有一定的灵活性。我是否应该在我的导演中使用 SetPegColors(vector colors, vector ratios) 等方法。谁的责任?我是否应该将这些方法保留在我的 PegBoard 中,并在构建过程后需要时调用它们?

或者构建器模式不是构建 Pegboard 我想要的方式的答案吗?

提前致谢!

我了解到您正在使用 Builder,因为您希望在创建时创建钉子并将其放入 PegBoard,以后不要修改.这是 Builder 模式的一个很好的用例。在这种情况下,提供像 setPegColors(..) 这样的方法会破坏设计。看起来您需要在 Builder 中使用 PegCreationStrategy。像这样(Java 语法):

public interface PegCreationStrategy {
   Peg[] getPegs(int n);
}

public class PrototypePegCreationStrategy {
    public PrototypePegCreationStrategy(Peg[] prototypes) {
    }

    @Override Peg[] getPegs(int n) {
    }
}

public class ColorRatioPegCreationStrategy {
    public ColorRatioPegCreationStrategy(vector colors, vector ratios) {
    }

    @Override Peg[] getPegs(int n) {
    }
}

public class PegBoard {
  public static class Builder {
    private int numPegs;
    private PegCreationStrategy strategy;
    Build withNumPegs(numPegs) {...}
    Builder withPegCreationStrategy(PegCreationStrategy s) {...}
    Builder withSomeOtherProperty(...) { ... }
    PegBoard build() { 
       Peg[] pegs = strategy.getPegs(numPegs);
       ...// other properties
       return new PegBoard(...);
  }
}

public static void main() {
    PegBoard pb = new PegBoard.Builder()
                    .withPegCreationStrategy(new ColorRatioPegCreationStrategy())
                    .withNumPegs(10)
                    .withSomeOtherProperty(...)
                    .build();
}