在哪里创建接口实现?

Where to create interface implementation?

我可能会问一个简单的 OO 设计问题。

想象一下,我们使用接口 (IHoo) 反转了两个具体 classes(Foo 和 Hoo)之间的依赖关系,其中 Hoo 实现接口,而 Foo 使用该实现。

那时,我想知道我应该在哪里将该实现 ( Hoo ) 附加到它的客户端 ( Foo )。显然,如果我们在客户端添加 Hoo class Foo,那么我们并没有反转编译时依赖(相对于运行时依赖),我们只是做了更多的模块化代码,但并没有那么严格。

因此,也许我们将客户端和接口实现关联到主控(或更高级别)class 中,例如控制器?你的方法是什么?

谢谢。

看一下composition root的概念。这是一切都应该连接起来的地方。

可以在实现仅在 运行 时间已知的情况下使用工厂。

为了补充其他答案,并解决 Where to create interface implementation? 的问题 GRASP Creator pattern 说(我已根据您的上下文对其进行了更改胡的):

A class B should be responsible for creating instances of class Hoo if one or more of the following apply:

  • Instances of B contain or compositely aggregate instances of Hoo
  • Instances of B record instances of Hoo
  • Instances of B closely use instances of Hoo
  • Instances of B have the initializing information for instances of Hoo and pass it on creation.

David Osborne 的回答指出(GRASP Creator 也是如此)您也可以使用工厂。