I have a GUI composend of a few JPanels. I want to use factory methods for the instantiation of the JPanels. Here a UML diagram showing what I want to do:
Simply put, the factory method needs to use methods from JPanel
and SimulatorSubscriber
, but if the createPanel()
method returns a JPanel
, SimulatorFactory
wont be able to call the setSimulator(Simulator)
method. Conversly, if it returns a SimulatorSubscriber
, it wont be able to add the panel to the gui it is making.
My first idea was to use casts........i don't need to elaborate..
Secondly, I thought to do what I drew in the diagram.
Is this good/common practice, and are there alternatives? Maybe my use of the factory method is off too.
I would clearly separate model and view.
So the factory can't at the same time create "business/model elements" like a simulator and UI elements like a SimulatorDisplay. So I would use two factories. One for business elements, one for UI elements.
I would avoid to use inheritence to solve every possible problem. So no longer make SimulatorDisplay inherit from JPanel. I would use a JPanel field in SimulatorDisplay and create a 'HasPanel' interface with getPanel() method inside it.
I would not provide directly a complete simulator to the subscribers, but use a real listener mechanism that provide only the public state of the simulator instead of the simulator itself.
In general, don't abuse Abstracts class and inheritence in java (exept maybe from interfaces). You are really limited has java don't support multiple inheritence. But even if it has, most of the time, this is not so usefull.