什么时候应该使用单例

什么时候应该使用单例

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

问题描述

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

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在,谈论服务定位器和客户端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.

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

08-11 07:28