In Java, how can I make a mutable object accessible to many objects that are not related to each other, without A) Creating mutable static fields / methods or B) Passing the same object to many layers, or which one is considered best practice for ease of maintenance, readability, etc.?
Two cases that often occur in my desktop applications:
User / session data in a graphical interface. The user starts subscribing at the beginning of the application, later I will need the username in JLabel inside the JPanel inside another panel inside another panel inside the JFrame. It seems ridiculous to pass my session data into a constructor of five or six layers in depth, but I hate the idea of an object that stores this information in static variables that are available all over the place.
Access to the database. I have one object to access the database, and all kinds of objects must then access the database. These classes are mostly unrelated and need a database for various reasons, so I resort to Databases.thisOne().query("...").
source
share