So I’m working on rewriting a program for a professor, and I have some questions related to the Model-View-Controller pattern. The program is called GraphViewer and is used to design and view graphs (as in Graph Theory, not Statistics). So far I have planned the structure thus:
- Models
- VertexModel – Has id, location, color, and a collection of edges it is coincident to
- EdgeModel – Has the two vertices it spans, weight, color, and a couple other things
- GraphModel – Primarily, but not just, a collection of vertices and a collection of edges
- Views
- VertexView – Paints its vertex, and has its own properties
- EdgeView – Paints its edge, and also has some of its own properties
- GraphView – Basically a JPanel that has a collection of vertex and edge views, when it gets a paint command, it also iterates through each collection of views and issues a paint command to them
- Controllers
- GraphController – Takes care of interpreting user gestures for adding vertices, edges, etc. and updates the model.
Now the first question I have is related to this plan: Should each model have a view–even though only the graphmodel is a JComponent? Now part of me says yes–because each vertex and edge might be drawn differently. But another part of me screams no to the kind-of parallel-list structure of a graphview having collections of views that correspond to models in the collections of the graphview’s graphmodel (boy that’s complicated). And somehow, I have to work in that the whole graphview must repaint if a vertex or edge model changes. I suppose the answer to this is also related to whether each model gets a controller. (Am I just approaching this wrong?)
Somewhat tied to the answer of the first question is my second: how will I know to notify the graphview if a vertexmodel is added to the graphmodel’s collection? If a whole new collection is set, it’ll notify the view when it enters the setEdges() method. But what if I have to write getEdges().add(…)? Now the graphview needs to be notified of an update, but setEdges was never called…
Thanks a bunch, as you can tell I’m kinda new to design patterns!
Don’t expose the private Collection member of the model, thus not allowing a call such as getEdges().add(…)
Rather, expose an API to allow adding/removing edges, and you can then make use of the Observer pattern to notify the view when the model changes.
Simplistically, and only dealing with Edges…