用于收集异类项的生成器模式

Builder Pattern for Collection of Heterogeneous Items

本文关键字:模式 异类 用于      更新时间:2023-10-16

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

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

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

  • 在某些情况下,我可能想拿一两个钉子,并告诉建造者制作n个副本并将它们随机放置在钉板上。

  • 在其他情况下,我可能希望显式提供具有初始化位置和属性的挂钩向量。

  • 我可能想创建一个带有 50% 红色钉子、50% 蓝色钉子或 20% 红色钉子和 80% 蓝色钉子等的钉板......我的理解是,对于构建器模式,我只能为我想要的每个(无限)可能的组合制作混凝土构建器。

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

还是构建器模式不是以我想要的方式构造Pegboard的答案?

提前感谢!

我知道

您正在使用 Builder,因为您希望在创建时创建钉子并将其放入PegBoard中,而不是以后修改。这是生成器模式的一个很好的用例。在这种情况下,提供像setPegColors(..)这样的方法会破坏设计。看起来您需要在构建器中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();
}