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

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

问题描述

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

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.

推荐答案

在寻求真相时,我发现使用Singleton的理由实际上很少。

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

一个经常在互联网上反复出现的原因是记录类的原因(您提到过)。在这种情况下,可以使用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."

我确定还有其他有效原因。 Alex Miller,在 我讨厌的模式,谈论服务定位器和客户端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 I上了解更多爱你,但你让我失望。

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

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