开发者

Java Sprite should be merged with Data Structure

I'm building my own Canvas-style JPanel subclass which will draw a graph of nodes and arcs. As part of this application I am delegating the drawing of the nodes to a sprite class Node, i.e

Class Visualiser extends JPanel {

    ...

    paintComponent(Graphics g) {
        ...
        node.draw(g);
        ...
    }
}

But I also have a class Node for a data structure. I'm not concerned about the nomenclature, I can call one NodeSprite to avoid conflicts, etc...

What I am wondering is whether t开发者_如何学Pythono merge the data structure and the sprite class into one, as logically they both describe the same real-world thing, or if doing this would have any negative side effects such as performance, or general bad design.

Any suggestions?


If a NodeSprite has behavior other than knowing how to print itself, it would violate the single responsibility principle. If all it knows how to do is draw, I would keep it that way and consider renaming it NodeSpritePrinter or something similar.


If a NodeSpite just draws a Node. Then I would be very tempted to combine them. Sometimes it makes good design sense to separate the view from the model, but there are definitely cases where doing that creates unnecessary complexity.

Also, Node sounds like a very generic name. It might be good to give it a more specific name anyway.


The downside would be mixing the painting code with the domain logic of the Node. That wouldn't be a disaster, but it would make the code less clear to read. The pattern of having parallel sets of classes for modelling the domain objects and their presentation is an old and honourable one, and indeed is used in the AWT itself - for every component, there's a corresponding 'native peer'. I'd take the two-classes approach; it separates responsibilities better, and has no real downside.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜