【问题标题】:Builder Pattern for Collection of Heterogeneous Items异构项集合的构建器模式
【发布时间】:2015-03-13 12:37:48
【问题描述】:

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

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

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

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

  • 在其他情况下,我可能想要显式地提供一个带有初始化位置和属性的钉子向量。

  • 我可能想创建一个带有 50% 红色钉子、50% 蓝色钉子或 20% 红色钉子和 80% 蓝色钉子等的钉板...我的理解是,我被构建器模式卡住了为我想要的每个(无限)可能的组合制作具体的构建器。

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

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

提前致谢!

【问题讨论】:

    标签: c++ oop design-patterns


    【解决方案1】:

    我了解您使用 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();
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多