单例强制类?
使用单例强制类的目的是什么?有人有如何创建/使用它们的示例吗?
有人告诉我可以使用这个想法来做全局变量(会话),是真的吗?
What's the purpose of using Singleton Enforced classes and does anyone have any examples of how to create/use them?
I was told I could do global variables (session) by using this idea, is it true?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
单例模式的目的是确保某个对象只存在一个实例。它通常在flex中用于将全局状态添加到项目中。换句话说,它允许您执行设置等操作,并可以从应用程序中的任何位置访问全局变量。
要使用此功能,您应该在应用程序的最高级别(main.mxml 或您的顶级级别)实例化您的 AppGlobals,方法如下:
然后,您可以在应用程序中的任何位置以相同的方式实例化 AppGlobals 的副本,并可以访问全球信息状态。
要回答问题的第二部分,是的,您可以使用它在应用程序中设置全局会话变量。有些人争论这是否是解决这个问题的最佳方法(当然并不适合每种情况),但我发现它很有用。
希望这有帮助!
The purpose of the Singleton Pattern is to make sure only a single instance of some object exists. It is usually used in flex to add Global State to a project. In other words, it allows you to do things like set and have access to global variables from anywhere in your application.
To use this, you should instantiate your AppGlobals at the highest level of your application (main.mxml or whatever your top level is), by doing something like this:
Then, anywhere in your application you can instantiate a copy of AppGlobals the same way, and have access to a global state of information.
To answer the second part of your question, yes, you can use this to setup global session variables in your application. Some people debate whether it is the best way to approach this (surely not ideal for every single situation), but I have found it useful.
Hope this helps!
请记住以下几点。 Singleton 不应该解决应用程序设计的不足并用作全局入口点。 Sinltone 的唯一有效用法是确保特定类只有一个实例(另请参阅 Multiton 来控制实例数量)。
所以在决定使用 Singleton 之前你应该三思而后行。您应该限制特定类的实例数量吗?如果存在多个单一实例怎么办——它会破坏域模型还是其他什么?
无论如何,不要使用单例和静态来解决架构问题以获得全局入口点。使用单音,您可以在未来重构应用程序时花费大量时间。
Just keep in mind the following. Singleton shouldn't solve lack of application design and used as global entry point. The only valid usage of Sinltone is ensure if there is only one instance of particular class (see also Multiton to control number of instances).
So you should think twice or even more times before deciding to use Singleton. Should you restrict number of instances of particular class? What if there will be more than one single instance — does it break domain model or something?
Anyway do not use Singletons and statics for solving architectural problems to have global entry point. Using Singltones you can spend a lot of time in future refactoring your application.