Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global Access in Java

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?

like image 557
Steve Avatar asked Feb 01 '11 19:02

Steve


2 Answers

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.

like image 160
Brian Agnew Avatar answered Sep 19 '22 06:09

Brian Agnew


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.

like image 41
Karthik Ramachandran Avatar answered Sep 21 '22 06:09

Karthik Ramachandran