美化的全局变量-变成一个美化的全局类。有人说打破面向对象设计。
给我一些场景,除了使用单例是有意义的良好的老记录器。
美化的全局变量-变成一个美化的全局类。有人说打破面向对象设计。
给我一些场景,除了使用单例是有意义的良好的老记录器。
当前回答
I use it for an object encapsulating command-line parameters when dealing with pluggable modules. The main program doesn't know what the command-line parameters are for modules that get loaded (and doesn't always even know what modules are being loaded). e.g., main loads A, which doesn't need any parameters itself (so why it should take an extra pointer / reference / whatever, I'm not sure - looks like pollution), then loads modules X, Y, and Z. Two of these, say X and Z, need (or accept) parameters, so they call back to the command-line singleton to tell it what parameters to accept, and the at runtime they call back to find out if the user actually has specified any of them.
在很多方面,处理CGI参数的单例方式与你每次查询只使用一个进程类似(其他mod_*方法不这样做,所以这很糟糕——因此这个参数说你不应该在mod_cgi世界中使用单例,以防你移植到mod_perl或其他世界)。
其他回答
当你加载一个配置属性对象时,无论是从数据库还是从文件中,将它作为一个单例都会有所帮助;没有理由在服务器运行时重新读取不会改变的静态数据。
Singleton类的主要目的是限制创建的实例数量,从而确保对资源的访问控制。
使用单例类不会产生内存空间浪费,因为它限制了实例的创建。因为对象的创建只会发生一次,而不是每次新请求时都创建。
单例类在内部使用互斥量,因此使其线程安全。这就是为什么多线程和数据库应用程序主要使用Java中的Singleton模式进行缓存、日志记录、线程池、配置设置等等
当您想要确保一个类将有一个实例,并且该实例将有一个全局访问点时,您可以使用单例设计模式。
假设您有一个应用程序,它需要数据库来处理CRUD操作。理想情况下,您应该使用与数据库相同的连接对象来访问数据库并执行CRUD操作。
因此,为了确保数据库类有一个对象,并且该对象将在整个应用程序中使用,我们实现了单例设计模式。
确保构造函数是私有的,并且提供了一个静态方法来提供对单例类的单个对象的访问
使用单例的方法之一是覆盖一个实例,其中必须有一个“代理”控制对资源的访问。单例在日志记录器中很好,因为它们代理访问,比如说,一个文件,这个文件只能被写入。对于像日志这样的东西,它们提供了一种方法来抽象出对日志文件之类的东西的写操作——你可以将缓存机制包装到你的单例中,等等……
也可以考虑这样一种情况,你有一个应用程序,有许多窗口/线程等,但它需要一个单一的通信点。我曾经使用它来控制我希望应用程序启动的作业。单例程序负责将作业序列化,并将它们的状态显示给程序中其他感兴趣的部分。在这种情况下,你可以把单例对象看作是在应用程序中运行的“服务器”类……HTH
I use it for an object encapsulating command-line parameters when dealing with pluggable modules. The main program doesn't know what the command-line parameters are for modules that get loaded (and doesn't always even know what modules are being loaded). e.g., main loads A, which doesn't need any parameters itself (so why it should take an extra pointer / reference / whatever, I'm not sure - looks like pollution), then loads modules X, Y, and Z. Two of these, say X and Z, need (or accept) parameters, so they call back to the command-line singleton to tell it what parameters to accept, and the at runtime they call back to find out if the user actually has specified any of them.
在很多方面,处理CGI参数的单例方式与你每次查询只使用一个进程类似(其他mod_*方法不这样做,所以这很糟糕——因此这个参数说你不应该在mod_cgi世界中使用单例,以防你移植到mod_perl或其他世界)。