设计模式:何时使用Singleton? [英] On Design Patterns: When to use the Singleton?

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

问题描述

荣耀的全球变量 - 成为一个荣耀的全球类。有些人说破坏面向对象设计。



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

解决方案

在我追求事实的同时,我发现使用Singleton实际上很少有可接受的理由。



在互联网上一次又一次地出现的一个原因是录音课(你提到的)。在这种情况下,可以使用Singleton而不是类的单个实例,因为日志类通常需要一次又一次地被项目中的每个类反复使用。如果每个类使用这个日志记录类,依赖注入变得麻烦。



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



我确定还有其他有效的理由。 Alex Miller在我讨厌的模式,服务定位器和客户端UI的谈话也可能是可接受的选择。



阅读更多在Singleton I爱你,但你把我带走了。


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.

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

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