Wednesday, 28 August 2013

Design Pattern for separating a model from its graphical representation

Design Pattern for separating a model from its graphical representation

The Problem
I am looking for (hopefully) a design pattern I might be ignorant of that
can help be accomplish some code-separation for the problem I've defined
below:
I have a set of classes that represent various entities such as Point,
Vector, Arc, etc., that belong on a 2D Cartesian plane, represented by a
class Model. The Model class acts as a collection for these entities as
well as storing useful calculated values.
I also have a visual interface that should render a 2D image of the state
of the model, and can also interact with the model to a small degree by
adding entities to the model (for instance, the user can add a Point to
the model by clicking on the GUI somewhere.).
First Idea
At first, I had an interface Drawable that had one method, Draw, that
would accept a graphics context object, and the implementing entity would
draw itself to that context using the graphics libraries I am using (Java
Swing/AWT in this case).
This worked well in that the GUI portion of my application simply had to
loop through all of the entities in my model and run their Draw method to
generate the visualization. The big problem was that I was marrying my
model to its graphical representation, and I feel like this bad practice.
Second Idea
I created a EntityDrawer class that would accept an entity, choose a
correct drawing method based on the type of entity, then draw to my
graphics context.
This approach accomplished the code-separation I was looking for, but the
EntityDrawer class relied heavily on an instanceOf/isA approach to
determine how to draw the entity, which I have repeatedly seen described
as poor design. I tried redesigning this so that class used overloaded
methods to determine which drawing method to use, but I realized that this
was basically the same instanceOf/isA approach written in a nicer looking
way. Also, for every new entity class that I add, I would need to mirror
that in this EntityDrawer's code, which feels like a form of coupling to
me.



I would like to have as much decoupling between my model and its graphical
representation as possible, so that the model can focus on modeling a
problem and not on how to render itself to a graphics context.
Furthermore, it is likely that I will be adding more model entity types in
the future that will have drastically different drawing needs.
So, is there a pattern or design technique I can use to accomplish this? I
feel like the two solutions I came up with are sub optimal and that there
is probably a design pattern out there that can take care of exactly this
kind of problem.

No comments:

Post a Comment