关于设计模式:我什么时候应该使用单例? [英] On design patterns: When should I use the singleton?

查看:29
本文介绍了关于设计模式:我什么时候应该使用单例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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."

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

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.

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

这篇关于关于设计模式:我什么时候应该使用单例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆