使用复合材料时如何确定并转换为特定对象?
我想要一个由 JSON 构建的复合结构。每个元素只能有一种类型的子元素 - 因此一个组只能包含组或只包含叶。然后,基于这棵树,我想绘制图形用户界面组件,该组件将根据其本身的类型(组或叶子)进行不同的渲染并运行不同的操作。
问题是如何确定要渲染的内容以及在绘图上附加哪些侦听器。树只是一个模型,因此它不应该包含进行图形或控制的方法。
检查它是否是某个实例并将组件转换为正确的类型然后进行正确的设置是好还是坏的做法?
使用枚举和吸气剂来确定它怎么样?
我知道可行的答案,但我想听到好的做法。
I would like to have a composite structure which is build from JSON. Each element can has only one type of children - so a group can contain only groups or only leaves. Then based on this tree I want to draw graphic user interface component, which will render diferrently and run different actions due to the type of itself (group or leaf).
The question is how to determine what to render and which listeners to attach on drawing. The tree is only a model, so it should not contain methods to do the graph or controlling.
Is it a good or bad pratice to check if it is instance of something and cast component to to right type and then do the right set up?
What about having a enum and getter to determine it?
I know answers that will work but I want to hear about good pratices.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我个人认为这将打破这种模式。
根据维基百科:
复合是一种帮助您将容器和叶子用作同一类型的模式。
看看这个图表。
我建议你在组件类中添加和抽象draw方法,并让其子类实现它。 Leaf 将有与 Composite 不同的实现。这样,遍历树的客户端类不需要知道节点是否是叶子,而可以简单地调用它的绘制方法。
Personally I think this will break the pattern.
Accordingly to wikipedia:
Composite is a pattern that help you to use both container and leaf as the same type.
Look this diagram.
I suggest you to add and abstract draw method to the component class and let its subclasses implement it. Leaf will have a different implementation than Composite. This way a client class traversing your tree doesn't need to be aware if a node is a Leaf or not, but can simply call draw method on it.