In Java, there is no global access like in C++. So what would one do if they wanted to create a container of objects that can be accessed from any class? Or say a java bean that holds global values.
For example, if I am making an elevator simulator, fields that need to be known by all like int numElevators
have to be place somewhere right? Same with the collection object for elevators Elevators[] elevators
.
I can think of one way which is to create a singleton class to store all those global variables. Then use static methods to provide access from any class. But is there a more elegant solution?
I would expect an instance of a Building
to have a collection of Elevators
. I think there are very few things in a project that are truly global and you can usually find some managing entity that should contain and distribute this knowledge.
By tying this within such an entity, you can a) control access and change/refactor more easily b) mock this and make testing easier.
I can think of one way which is to create a singleton class to store all those global variables. Then use static methods to provide access from any class. But is there a more elegant solution?
Nope, that's the way to do it. A combination of static methods and singletons.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With