重新设计循环依赖缺陷 [英] re-design circular dependency flaw

查看:95
本文介绍了重新设计循环依赖缺陷的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆小型服务,它们共享一些常见的软件包,例如 Logger Configuration 。然后,我在单独的项目中编写了每个程序包。
问题是我的 Logger 需要软件包 Configuration 进行设置。我的配置不是仅由 Logger 单独使用)想要在必要时编写输出日志

I've a bunch of small services that share some common packages like Logger, Configuration and Net. And I wrote each package in separated project. The issue is that my Logger needs package Configuration for set up. And my Configuration (not solely used by Logger) wants to write output log when necessary.

因此,我有循环依赖缺陷 Logger -> 配置配置 -> 记录器

Therefore, I've circular dependency flaw Logger-->Configuration, Configuration-->Logger.

如何重新设计此代码?

推荐答案

有什么问题与类似的情况发生在今年的GopherCon上,爱德华·穆勒(Edward Muller)认为,具有配置结构会增加应用程序中的耦合。配置包只是其中的一个极端版本。他认为,相依性应该只接受它实际需要的配置位,而不是整个结构(在这种情况下为包)。您可以在此处查看他的演讲的这一部分:

Something similar to this came up at GopherCon this year where Edward Muller argued that having config structs increased coupling in your application. The configuration package is just an extreme version of this. He argued that instead the dependency should just take in the bits of the configuration that it actually needs rather than the whole struct (or package in this case). You can see this part of his talk here:

https://www.youtube.com/watch?v=ltqV6pDKZD8

或此处的文字版本:

https://about.sourcegraph.com / go / idiomatic-go /#config-structs

他的解决方案的实质是让您主要执行以下操作:

The essence of his solution would be to have you main do something like:

logSetting1 := configuration.GetLogSetting1()
logSetting2 := configuration.GetLogSetting2()
logger.SetSettings(logSetting1, logSetting2)

如果您的记录器需要以下设置,您可能还会遇到首先创建的内容问题配置以初始化自身。通过创建具有合理默认值的记录器,使用默认记录器创建配置对象,然后根据加载的配置调整记录器,可以避免这种情况。这意味着您暂时有一个配置不正确的记录器,但是您使用它做的 only 只是用来记录配置的加载情况。

You will probably also have a "what gets created first" problem if your logger needs some settings from the config in order to initialize itself. I avoid this by creating a logger with sensible defaults, creating the configuration object using the default logger then adjusting the logger based on the loaded configuration. This means that you temporally have a logger that isn't configured correctly but the only thing you do with it is use it for logging the loading of the configuration.

这篇关于重新设计循环依赖缺陷的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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