开发者

Global Access in Java

开发者 https://www.devze.com 2023-02-08 12:02 出处:网络
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.

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 k开发者_JS百科nown 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.


You could create a non-singleton class with the desired fields, and provide an instance of this to whatever needs it.

Minimizing the amount of your code that presumes a single such context makes it easier to adapt later to multiple contexts.

For example, you might begin with a single set of elevators, but later want multiple sets, for different towers or buildings.


You can create a class with a bunch of public static fields. Something like

class AppGlobals {
   public static final String IMPORTANT_STUFF = "something global...";
   ....

}

Or you can read in a properties configuration to get simple data like Strings and whatnot.

You can also combine 1 and 2.

Edit -- for your elevator/buildings example, proper OO design would eliminate the need for globals....


You might want to look into the Monostate Design Paradigm if you are shying away from Singleton. Here's a good StackOverflow question on it.

Monostate vs. Singleton

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号