I've a main class that contains main method as well as start method. Now I've a lot of other classes also. For example I've a login class, signup class and so on. I've a class that just handles the data of currently logged on user. that class is needed to be accessed from a lot of controllers. As this user is always gonna be only one so one instance of class. What i want to know what is the best approach so every class can access it update it.
What I'm currently applying is I'm making a static instance of logged user data type class in my main class. and then accessing them.
public static loggedUserData user = new loggedUserData();
then accessing it from anywhere as:
demo.user.set(...);
While class methods and fields are non static. I think there could be a better way to resolve this.
Your
user
object is application data that forms part of the model in MVC/MVP etc designs:In relatively simple applications, I create a singleton controller factory that references a model instance and passes it to any controller constructor that can accept it:
(Another option, instead of using a singleton pattern here, is just to have a constructor that accepts a
DataModel
and be careful to always pass a reference to the sameDataModel
instance. Often it is quite natural to do this.)Then you can have controllers that look like
and
The controllers will be automatically populated with the (shared) data model if you use the following idiom to load your FXML files:
For more complex applications (or simply if you prefer a convention-based/opinionated approach), consider using a dedicated JavaFX dependency injection framework such as Afterburner.fx.