关于设计模式。什么时候使用Singleton?[英] On Design Patterns: When to use the Singleton?

本文是小编为大家收集整理的关于关于设计模式。什么时候使用Singleton?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

荣耀的全局变量 - 成为荣耀的全局类.有人说打破了面向对象设计.

给我一​​些场景,除了使用单例的好旧记录器.

推荐答案

在追寻真相的过程中,我发现实际上很少有"可接受"的理由来使用 Singleton.

互联网上反复出现的一个原因是"日志记录"类(您提到过).在这种情况下,可以使用 Singleton 来代替类的单个实例,因为项目中的每个类通常需要一遍又一遍地使用日志记录类.如果每个类都使用这个日志类,依赖注入就变得很麻烦了.

日志记录是"可接受的"单例的一个具体示例,因为它不会影响代码的执行.禁用日志记录,代码执行保持不变.启用它,同样的.Misko 在 Singletons 的根本原因, "这里的信息流向一种方式:从您的应用程序到记录器.即使记录器是全局状态,由于没有信息从记录器流入您的应用程序,记录器是可以接受的."

我相信还有其他正当理由.亚历克斯·米勒,在"我讨厌的模式",关于服务定位器和客户端 UI 的讨论也可能是"可接受的"选择.

在 Singleton 阅读更多我爱你,但你让我失望了.

本文地址:https://www.itbaoku.cn/post/627443.html

问题描述

The glorified global variable - becomes a gloried global class. Some say breaking Object Oriented Design.

Give me scenarios, other than the good old logger where it makes sense to use the singleton.

推荐答案

On my quest for the truth I discovered that there are actually very few "acceptable" reasons to use a Singleton.

One reason that tends to come up over and over again on the internets is that of a "logging" class (which you mentioned). In this case, a Singleton can be used instead of a single instance of a class because a logging class usually needs to be used over and over again ad nauseam by every class in a project. If every class uses this logging class, dependency injection becomes cumbersome.

Logging is a specific example of an "acceptable" Singleton because it doesn't affect the execution of your code. Disable logging, code execution remains the same. Enable it, same same. Misko puts it in the following way in Root Cause of Singletons, "The information here flows one way: From your application into the logger. Even though loggers are global state, since no information flows from loggers into your application, loggers are acceptable."

I'm sure there are other valid reasons as well. Alex Miller, in "Patterns I Hate", talks of service locators and client side UI's also being possibly "acceptable" choices.

Read more at Singleton I love you, but you're bringing me down.