美化的全局变量-变成一个美化的全局类。有人说打破面向对象设计。
给我一些场景,除了使用单例是有意义的良好的老记录器。
美化的全局变量-变成一个美化的全局类。有人说打破面向对象设计。
给我一些场景,除了使用单例是有意义的良好的老记录器。
当前回答
单例候选人必须满足三个要求:
控制对共享资源的并发访问。 将从系统的多个不同部分请求对资源的访问。 只能有一个对象。
如果你提议的单例只有其中的一两个需求,那么重新设计几乎总是正确的选择。
例如,打印机假脱机程序不太可能从多个位置(打印菜单)调用,因此可以使用互斥来解决并发访问问题。
简单的日志记录器是可能有效的单例的最明显的例子,但这可能会在更复杂的日志记录方案中发生变化。
其他回答
管理到数据库的连接(或连接池)。
我还会使用它来检索和存储外部配置文件中的信息。
当需要管理共享资源时,可以使用单例。例如打印机假脱机程序。您的应用程序应该只有一个假脱机程序实例,以避免对相同资源的请求冲突。
或者数据库连接或者文件管理器等等。
一个实例可以在Test::Builder中找到,这个类支持几乎所有现代Perl测试模块。Builder单例存储并代理测试流程的状态和历史记录(历史测试结果,计算运行的测试次数)以及测试输出流向等内容。这些都是协调由不同作者编写的多个测试模块以在单个测试脚本中一起工作所必需的。
The history of Test::Builder's singleton is educational. Calling new() always gives you the same object. First, all the data was stored as class variables with nothing in the object itself. This worked until I wanted to test Test::Builder with itself. Then I needed two Test::Builder objects, one setup as a dummy, to capture and test its behavior and output, and one to be the real test object. At that point Test::Builder was refactored into a real object. The singleton object was stored as class data, and new() would always return it. create() was added to make a fresh object and enable testing.
Currently, users are wanting to change some behaviors of Test::Builder in their own module, but leave others alone, while the test history remains in common across all testing modules. What's happening now is the monolithic Test::Builder object is being broken down into smaller pieces (history, output, format...) with a Test::Builder instance collecting them together. Now Test::Builder no longer has to be a singleton. Its components, like history, can be. This pushes the inflexible necessity of a singleton down a level. It gives more flexibility to the user to mix-and-match pieces. The smaller singleton objects can now just store data, with their containing objects deciding how to use it. It even allows a non-Test::Builder class to play along by using the Test::Builder history and output singletons.
似乎在数据的协调和行为的灵活性之间存在着一种推拉关系,这种关系可以通过在共享数据周围使用尽可能少的行为来缓解,以确保数据的完整性。
因此,我正在为学校阅读单例模式,教授们策划了一份关于该主题的当前观点和最佳实践的列表。似乎有一个共识,即如果构建时不向代码中添加任何内容,则可以使用单例。如果您使单例使用可以被开启和关闭,并且除了工作负载之外没有其他副作用,那么使用这种设计模式是安全的,也是可取的。
Singleton类的主要目的是限制创建的实例数量,从而确保对资源的访问控制。
使用单例类不会产生内存空间浪费,因为它限制了实例的创建。因为对象的创建只会发生一次,而不是每次新请求时都创建。
单例类在内部使用互斥量,因此使其线程安全。这就是为什么多线程和数据库应用程序主要使用Java中的Singleton模式进行缓存、日志记录、线程池、配置设置等等