Search code examples
javadatamodeljinternalframejdesktoppane

Shared object between multiple JInternalFrames


What's the most efficient method of implementing a shared data object between multiple JInternalFrames on a single JDesktopPane?

Not sure whether to go with singleton or can I put a data object in the JDesktopPane and access from a component? I don't want to keep separate instances of this data for each frame (lots of frames)


Solution

  • I would steer clear of singleton (as it's a-kin to using global variables - See here for a description) and instead subclass JInternalFrame to contain a reference to the shared data object; e.g.

    public class MyInternalFrame extends JInternalFrame {
      private final SharedData data;
    
      public MyInternalFrame(SharedData data) {
        this.data = data;
      }
    }
    

    Obviously despite having multiple references to your SharedData (one per MyInternalFrame instance) there is still only one SharedData object in your system; i.e. you are not duplicating data with this approach.