开发者

How to determine and cast to specific object of composite while using it?

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.


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?

Personally I think this will break the pattern. Accordingly to wikipedia:

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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜