I would handle this situation by building a factory method that produces the right type of Swing component for any given ReportElement
, like this:
public static JComponent buildViewForReportElement(ReportElement element)
Inside this method, you will need to actually inspect the ReportElement
objects to see what type of component to build. This inspection might mean checking a field or a flag on each object, or might even mean using instanceof
to distinguish different subclasses of ReportElement
from one another.
Note that inspecting ReportElement
objects like this violates the philosophy of object-oriented programming. A simple "object-oriented" solution would require all of your ReportElement
objects to have a buildView()
or getView()
method, and so your GUI code could just call getView()
on every ReportElement
without knowing which implementation of getView()
was actually being called.
Unfortunately, the object-oriented solution forces you to mix your view code with your model code, and it's good that you are trying to keep the two separate. That's why I would advocate keeping the GUI-building code out of ReportElement
objects and instead using a factory method to build the right view for any given ReportElement
.