gpt4 book ai didi

design-patterns - 为什么我们应该将«Logger»类视为单例呢?

转载 作者:行者123 更新时间:2023-12-04 03:02:31 27 4
gpt4 key购买 nike

我们都知道log,好吧,但是为什么我们要把«Logger»类看作单例呢?如果我们将其作为普通的非单例类怎么办?

最佳答案

我在IBM网站上找到了这个。它很好地解释了Logger Singleton类的用法。

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.


这里的链接: Use your singletons wisely

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

关于design-patterns - 为什么我们应该将«Logger»类视为单例呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4085463/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com