gpt4 book ai didi

谷歌/电线 : Is this a use case for the Singleton pattern?

转载 作者:IT王子 更新时间:2023-10-29 00:46:54 28 4
gpt4 key购买 nike

以下代码段声明了两个具有共同依赖关系的 google/wire 初始化程序。强制只创建一个配置实例的最佳方法是什么?

我可以将共享依赖项向下传递给 InitializeStorageHandler 函数,但如果我的理解是正确的,那将破坏 DI 的目的。

当然,我也可以使用单例模式。我不确定这是否是做事的“Go-Way”。有最佳实践吗?

package api

import (
"../storage"
"../config"
"github.com/google/wire"
)

func InitializeServer() (*Server, error) {
panic(wire.Build(config.NewConfiguration, NewServer))
}

func InitializeStorageHandler() *StorageHandler {
panic(wire.Build(config.NewConfiguration, storage.NewStorage, storage.NewService, NewStorageHandler))
}

最佳答案

Of course, I could also use the Singleton pattern

这与 wire 一致,如 issue 77 ,其中提到“Wire 非常适合提供单例”。

issue 21 中所述:

Wire intentionally does not have a notion of subcomponents at the moment.
In talking with the Dagger team, we discovered that subcomponents and scopes introduce a fair amount of complexity.

As you say, you can get much the same behavior by returning the singletons from the first injector that creates them and then pass them to later injectors. This has the benefit of making the dataflow explicit, which for the examples we came up with, seemed like a net win.
That said, we're very curious to see how folks will use Wire in real-world applications: if this does not scale, we might have to revisit.

I realized after looking more closely at your sample that the component itself is stateful (a detail I had forgotten about Dagger). My explanation above is still largely applicable: we want state to be explicit.

在这种情况下,从 How singleton pattern works with Golang 中检查“Jefferson Otoni Lima ” : sync.Onceinit() function可以帮助在“Go-way”中安全地构建单例。

关于谷歌/电线 : Is this a use case for the Singleton pattern?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54963188/

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