单例设计模式
可能的重复:
如何在 Web 应用程序中处理单例?
是单例设计吗?模式为 JVM 创建单个实例还是为应用程序创建单个实例?
Possible Duplicate:
How are singletons handled in a web application?
Is singleton design pattern creates single instance for JVM or single instance for an application?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可能会发现这个SO线程很有用。
You might find this SO thread useful.
每个正在运行的应用程序都是一个实例
It's a single instance per running application
单例设计模式通常在类级别实现,但也可以在应用程序级别实现。我相信一次只有一个 JVM 实例在运行。
Singleton design pattern is typically implemented at the class level, though it could be implemented at the application level. I believe there is only ever one JVM instance running at a time.
问题不清楚。什么是“应用程序”?
Word 或 Excel 等程序是应用程序,Apache Web 服务器也是应用程序之一。
如果您有一些用 Java 实现的程序,通常每个程序都启动自己的 JVM ...通常强调
您可以轻松找到在同一个 JVM 中运行多个应用程序的方法。例如,这是在“应用程序服务器”或“Web 服务器”/servlet 容器中完成的。
正如上面有人指出的:每个类加载器将有一个单例。
在应用程序服务器/应用程序容器/Web 容器中,每个“应用程序”都分配有自己的类 laoder。因此,每个应用程序都有一个单例(因为它的类加载器)。
如果您的 JVM 上只有一个应用程序或只有一个类加载器,那么您显然只有一个单例。
The question is unclear. What is an "application"?
Programs like Word or Excel are applications, also an Apache web server is one.
If you have some programs that are implemented in Java, usually each of them is starting its own JVM ... emphasize on usually
You can easy find ways to run several applications inside the same JVM. E.g. this is done in "application servers" or "web servers"/servlet containers.
As someone above pointed out: you will have one singleton per Class Loader.
In an application server/app container/web container every "application" gets its own class laoder asigned. So you have one singleton per Application (because of its Class Loader).
If you have only one application on your JVM or only one Class Loader you obviously only have one singleton.
它是应用程序的一个正在运行的实例的一个单例实例。不过,应用程序的每个运行实例都会有自己的 JVM。因此,实际上,每个 JVM 都有自己的单例实例。
Its one singleton instance for one running instance of the application. Each running instance of your application will get its own JVM though. So, effectively, each JVM has its own instance of your singleton.
Singleton 的实现基于使用方法(或 .NET 中的属性)创建一个类,如果该类的实例尚不存在,则创建该类的实例。类的构造函数必须是私有的,以防止其他方式的初始化。
有关更多详细信息,我建议您阅读这篇文章。
The implementation of Singleton based on creation a class with a method(or property in .NET) that creates an instance of this class if one doesn't exists yet. The constructor of class must be private to prevent other ways of initialization.
For more details I recommand you to read this article.