存储整个程序使用的信息的最佳方式?
假设我有一些程序范围的信息,例如程序的根目录或所选的语言,我希望用户能够更改这些信息。我应该如何最好地以一种可以随时为程序的任何部分轻松访问的形式存储这些信息?
我正在考虑使用存储在单个文件中的全局变量,该文件可以被需要该信息的其他文件包含。这样,我只需要更改该全局变量的值,整个程序就可以像以前一样访问新值。但是,恐怕使用这样的全局变量是不好的做法。您对此有何看法?
(另外,我认为这与语言无关,但如果有不同的最佳方法可以用不同的语言实现这一点,我也想听听)
Say I have some program-wide information, like the root directory of the program or the language selected, that I would like the user to be able to change. How should I best go about storing this information in a form easily accessible at any time for any part of the program?
I was thinking of using global variables stored inside an individual file that could be included by other files that need the information. This way, I would just need to change the value of that global variable and the whole program could access the new value as it did before. However, I am afraid that using such global variables would be bad practice. What are your thoughts on this?
(Also, I thought that this would be language-agnostic, but if there are different best ways of accomplishing this in different languages, I would like to hear about that as well)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以创建一个称为共享控制器的东西来存储复杂的信息(使用一些方法来创建/更新/删除信息)。它可以按照单例模式来实现。 Objective-C 开发人员经常使用这种做法来跨应用程序存储全局对象。
You may create a thing called shared controller for complex information storage (with some methods to create/update/delete the information). It can be implemented following the singleton pattern. Objective-C developers often use that practice to store global objects across application.
听起来像是一个首选项 API。如今,几乎每个重要的应用程序框架都提供一个甚至多个。例如,其中一个是核心 Java API 的一部分,另一个是 Eclipse 框架的一部分。 Windows 有注册表,您可以从该平台上的任何语言使用它,等等。这些东西通常是结构化的,因此您可以使用一个静态工厂方法来获取应用程序的首选项存储,然后您可以从任何地方。
Sounds like a preferences API. Virtually every nontrivial application framework offers one these days, or even several. There's one as part of the core Java API, for example, and another as part of the Eclipse framework. Windows has the registry, which you can use from any language on that platform, etc. These things are normally structured so there's a static factory method you use to get ahold of the preference store for the application, and then you can interact with it from anywhere.