为什么我们应该使用与使用它们的类接口,而不是实现它们的接口? [英] Why should we place interfaces with classes that use them rather than those that implement them?

查看:109
本文介绍了为什么我们应该使用与使用它们的类接口,而不是实现它们的接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在经历Robert C. Martin的一篇文章,他在一个地方给了一个这样的例子:



第一张图片显示,这两个包。要删除此依赖关系,将在第二个映像中添加一个新界面。 B实现接口,Y使用它。 Martin提出以下几点:


界面通常被包含在使用它们的包中,而不是在
的包中


我的问题是,为什么要这样安排界面?包装接口背后的原因是什么?根据共同关闭原则,一起变化的课程应该保持在一起。更接近实现者或其用户的界面?



解决方案

从技术上讲,用户没有接近界面实现者。在变更方面,当界面发生变化时,两者都需要更改。



但是,为什么界面会改变?



用户调用一个接口,因此它可以独立于可用的任何实现者。因此,接口的定义由用户的需要决定。



由于用户指定接口的定义,如果用户没有改变接口不需要它需要更改接口以适应实现的实现者应该发送红旗。为什么需要更多或不同的用户信息?对用户有什么用途?



此外,实现者只是依赖于接口,它需要为每个方法提供实现接口。但是可以自由地提供空的存根,实质上是向其客户端提供NOP。



所以,用户需要驱动对界面的更改,并更改界面驱动器的更改给执行者。因此,用户在功能上比实现者更接近接口。这是一个很好的例子来声明与用户的接口而不是实现者。


I was going through an article by Robert C. Martin and at one place he gave a example like this:

The first image shows that there's a cyclic dependency between the two packages. To remove this dependency a new interface is added in the second image. B implements the interface and Y uses it. And Martin makes the following point:

Interfaces are very often included in the package that uses them, rather than in the package that implements them.

My question is, why should we arrange interfaces this way? What is the reasoning behind packaging interfaces this way? According to Common Closure Principle classes that change together should stay together. Is an interface closer to its implementer or its user, in terms of change???

解决方案

Technically, the user is no closer to the interface than the implementor. In terms of change both will need to change when the interface changes.

However, why would the interface change?

The user calls to an interface so it can be independent of whatever implementor is available. Therefore the definition of the interface is dictated by the needs of the user.

As the user dictates the definition of the interface, there is no point changing the interface if the user doesn't need it. An implementor requiring a change to the interface to accommodate the implementation should send up red flags. Why does it need more or different information from the user? What use is that to the user?

Also, the implementor "merely" depends on the interface in as much as it needs to provide implementations for each of the methods in the interface. But it is free to provide empty stubs, in essence delivering a NOP to its clients.

So, the user's needs drive changes to the interface and changes to the interface drive changes to the implementor(s). As such the user is functionally much closer to the interface than the implementor. Which makes a good case to declare the interface with the user and not the implementor.

这篇关于为什么我们应该使用与使用它们的类接口,而不是实现它们的接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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