Java 中的全局访问
在 Java 中,没有像 C++ 那样的全局访问。那么,如果人们想要创建一个可以从任何类访问的对象容器,该怎么办呢?或者说一个保存全局值的 java bean。
例如,如果我正在制作一个电梯模拟器,那么像 int numElevators
这样需要所有人都知道的字段必须放置在某个地方,对吧?与电梯Elevators[]电梯
的集合对象相同。
我可以想到一种方法,那就是创建一个单例类来存储所有这些全局变量。然后使用静态方法提供从任何类的访问。但还有更优雅的解决方案吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我希望
Building
的实例具有一组Elevators
。我认为项目中很少有真正全球化的东西,您通常可以找到一些应该包含和分发这些知识的管理实体。通过将其绑定到这样的实体中,您可以a)更轻松地控制访问和更改/重构b)模拟它并使测试更容易。
I would expect an instance of a
Building
to have a collection ofElevators
. 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.
不,这就是这样做的方法。静态方法和单例的组合。
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.
您可以创建一个包含一堆公共静态字段的类。或者
您可以读取属性配置来获取简单的数据,例如字符串等。
您还可以结合 1 和 2。
编辑 - 对于您的电梯/建筑物示例,正确的 OO 设计将消除对全局变量的需要......
You can create a class with a bunch of public static fields. Something like
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....
如果您回避 Singleton,您可能需要研究 Monostate 设计范式。这是一个很好的 StackOverflow 问题。
单态与单例
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