为什么我们应该将“记录器”类作为单身人士考虑? [英] Why we should consider the «Logger» class as a singleton?

查看:96
本文介绍了为什么我们应该将“记录器”类作为单身人士考虑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们都知道日志,好的,但是为什么我们应该把记录器类视为一个单例呢?如果我们把它作为一个普通的 --singleton类,会发生什么?

解决方案

我发现这里在IBM网站上。它解释了Logger Singleton类的用法。


一个真正的单例的经典例子
是一个日志记录服务。假设我们有
一个基于事件的日志记录服务:客户端
对象请求文本由
记录发送消息到日志
服务。其他对象实际上通过监听这些日志记录请求的日志
服务和
处理它们,将文本记录在某处(console,file,
whatever)。首先,请注意,
日志服务通过经典的
测试作为一个单例:




  • 请求者需要一个众所周知的对象向
    日志发送请求。这意味着
    访问的全局点。

  • 由于日志记录服务是单个事件源,多个
    监听器可以注册,只有
    需要作为一个例子。


这里的链接:明智地使用你的单身人士



使用一个单例类,你必须处理这些不同的记录器实例之间的同步(写入一个文件或者你使用的任何流)。因此,当您只有一个全局Logger实例时,它更容易。


We all know about log, ok, but why should we consider the «Logger» class a singleton one? What happens if we make it as a normal non-singleton class?

解决方案

I found this here on the IBM site. It explains the usage of a Logger Singleton class quite well.

A classic example of a true singleton is a logging service. Suppose we have an event-based logging service: Client objects request that text be logged by sending a message to the logging service. Other objects actually log the text somewhere (console, file, whatever) by listening to the logging service for these logging requests and handling them. First, notice that the logging service passes the classic test for being a singleton:

  • The requesters need a well-known object to which to send requests to log. This means a global point of access.
  • Since the logging service is a single event source to which multiple listeners can register, there only needs to be one instance.

Here the link: Use your singletons wisely

If you wouldn't use a singleton class you would have to deal with the synchronisation (writing to a file, or whatever stream you use) between these different logger instances. So its much easier, when you just have one global Logger instance.

这篇关于为什么我们应该将“记录器”类作为单身人士考虑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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