用于收集异类项的生成器模式
Builder Pattern for Collection of Heterogeneous Items
我正在尝试找出为异构项目集合(在数据中,而不是在类型中)设置构建器的正确方法。
假设我有一个想要建造的钉板。钉板包含一个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();
}
相关文章:
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 为什么在保护模式下继承升级不起作用
- 如何在全屏模式下(在OpenGL中)使背景透明
- 为什么使用__LINE_的代码在发布模式下在MSVC下编译,而不是在调试模式下
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 此模式的C++RegEx
- avrogencpp能为模式中的每种类型生成单独的头文件吗
- 使用可变模板的Broadcaster/Listener模式
- c++方法参数只能在linux的发布模式下自行更改
- 资源管理设计模式
- 使用 mod_gsoap 部署服务时,如何在 Gsoap 中更改 soap 上下文的模式?
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 小字符串优化(调试与发布模式)
- 可视化C++:发布模式的运行时库作为'Multi-threaded Debug DLL'
- 如何设计具有不同类型的通知和观察器的观察者模式?
- 在C++的一系列数字中查找重复模式
- 是否允许使用带有"w+"模式的 freopen 进行标准设置?
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- С++ wxWidgets:代码架构,设计原则和模式
- 用于收集异类项的生成器模式