Implementing Publish/Subscribe and Observer Patterns in Java

designjavaobserver-patternswing

I'm developing desktop application in java/swing.

I have a component that is registered as a subscriber to many panels and gets messages (my custom event) from them. That component is something like message tray. When there is a validation error or some kind of info message it's delivered from panel to that tray by my "publish" method.

But now I'm facing a problem.
I have window that consist my message tray and internal panel.
in this internal panel there are some components and other Panel.
And in this Panel there are panels that implements Publisher interface but
they are being created on the fly from metadata and I don't have access to them to register subscriber.

So I cannot directly register my message tray as subscriber to panels because:

  1. I don't have access to them
  2. they are created dynamically from metadata and can change.

Is it ok to set my subscriber object reference in the middle (between) panels, and when creating dynamically my publisher panels register that reference to them?

Is it ok with the observer pattern because now other classes have reference to the object that they don't strictly need.

Maybe this object should be injected in other way?
or maybe it is all OK and I just messed my mind today 😉

Picture to make it clearer

Best Answer

There are two possibilities:

  1. Pass the "message tray" to whatever component needs it
  2. Make each component that can have controls implement the "tray" interface. That way, the holder of the internal panels is also a tray and it can dispatch the messages to it's parent tray (if any).

I like more #2 because it allows you to be more flexible in how the controls hierarchy looks like (aka, a control that is tray might decide that only some messages are passed to parents). Also, in this design, each child has only a reference to the parent and the parent decides what to do with the incoming messages.