Swing and Design Patterns – Part 4. Mediator Pattern

Assume we have a component hierarchy that looks like the following diagram. Some component on one branch (say a button), wants to update something on another branch (say text in a text field).


This scenario occurs very often in complex GUIs. Some examples may be :

  • Blinking of a mail icon when mail is recieved.
  • Update a table cell of a trade, after closing it in a dialog.
  • Any inner-framed application that requires inter frame communication (like photoshop)

To solve this communication dillema we can ‘bubble’ through a reference to the parent frame. In the constructor of the container components we pass this reference through.

We thread the parent frame through the constructor of our initial panel.

We want this parent frame to permeate all our components so we keep passing it through the constructors of embedded panels :

…and so on. Lets assume the class AnotherPanel calls a Dialog. The parent frame object also needs to be passed through the dialog too :

The dialog embeds yet another panel, and threads the frame through.

Notice that each embedded panel/dialog has a getter method associated with it.

The whole point to this is that we can access any node in the hierarchy from any other node. Assume we are in some other part of the GUI hierarchy. Since we have a handle to the parent frame, we can make a call like this, which in our hypothetical situation would blink some text.





The Mediator Pattern is Really Just a Thread-Safe Singleton

To overcome a lot of the bloat that the previously described technique describes, use a thread safe singleton to hold any interested components.

This singleton object contains all the components that we are interested in. This kills the bloat as we don’t need getters for all the panels, these horrible chained method calls, and passing the frame through all the constructors.

In the constructor of our interested objects we add it to the constructor like this :

…then in some far away panel we can use the mediator to access this panel, and call a hypothetical method called blinkSomeText().

Some find the way the singleton holds references to the components is a little bloated. It is fairly bloated, and another option would be to store all these references as a map, and access the components using get and put from the map object. It’s a matter of taste.

Further reading:

Posted in Design Pattern, Swing, Swing Design Pattern | Tagged , , , | Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">