java - 使用复合 Material 时如何确定并转换为特定对象?

标签 java design-patterns composite

我想要一个由 JSON 构建的复合结构。每个元素只能有一种类型的子元素 - 因此一个组只能包含组或只包含叶。然后基于这棵树,我想绘制图形用户界面组件,该组件将根据其自身的类型(组或叶)而呈现不同的效果并运行不同的操作。

问题是如何确定要渲染的内容以及在绘图上附加哪些监听器。树只是一个模型,因此它不应该包含进行图形或控制的方法。

检查它是否是某物的实例并将组件转换为正确的类型,然后进行正确的设置,这是一个好还是坏的做法?

使用枚举和 getter 来确定它怎么样?

我知道可行的答案,但我想听到好的做法。

最佳答案

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?

我个人认为这会打破这种模式。 根据维基百科:

When dealing with tree-structured data, programmers often have to discriminate between a leaf-node and a branch. This makes code more complex, and therefore, error prone. The solution is an interface that allows treating complex and primitive objects uniformly. In object-oriented programming, a composite is an object designed as a composition of one-or-more similar objects, all exhibiting similar functionality.

复合是一种帮助您将容器和叶子用作同一类型的模式。 看这个diagram .

我建议你在组件类中添加并抽象draw方法,并让其子类实现它。 Leaf 将有与 Composite 不同的实现。这样,遍历树的客户端类不需要知道节点是否是叶子,而可以简单地调用它的绘制方法。

关于java - 使用复合 Material 时如何确定并转换为特定对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7263174/

相关文章:

java - 来自扩展 RealmObject 的类的 IllegalArgumentException (java)

java - 应用中存在一个生产者多个消费者时apache kafka如何处理一致性

java - 二叉树,在前序遍历中返回下一个节点

asp.net-mvc - MVC 和 MVVM 有什么区别和相似之处?

java - 如何让内容显示在 ScrolledComposite 中

java - Maven如何根据平台配置更改依赖版本(MySQL)

JavaScript 库模式

Python 设计模式 : using class attributes to store data vs. 局部函数变量

python - 使用 sqlalchemy 的复合键关系

components - 用于基于组件(或复合)的 Web 应用程序的 OpenRasta 框架