接口如何促进代码的可重用性?
一个简单的面试问题。 接口如何帮助代码重用?
A simple interview question.
How do interfaces help with code reusablity?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
一个简单的面试问题。 接口如何帮助代码重用?
A simple interview question.
How do interfaces help with code reusablity?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(3)
接口允许您将实现与调用类关心的信息分开。这使您能够将您的类与其所依赖的类的深入知识分离。
给定以下
接口
:可以针对所述接口对依赖类进行编程,并“屏蔽”细节。
利用此模式使您能够创建所述接口的不同实现:
interface
s allows you to separate the implementation from the information the calling class cares about. This enables you to de-couple your classes from having intimate knowledge of classes it depends on.Given the following
interface
:A dependent class can be programmed against said interface and be "shielded" from the details.
Utilizing this pattern enables you to create different implementations of said interface:
接口将使用者与类的实现细节解耦。这有助于实现可重用性,因为实现接口的类可以更改,而无需更改使用实现的代码。
这很令人困惑,也许一个例子有帮助
现在我将编写消费者,它不关心如何执行身份验证,它只是知道它可以对用户进行身份验证。
无论 IUserAuthentication 服务的实现如何,上面的代码都将起作用。这是重用代码的一种方法。
现在我可以实现 IUserAuthentication 接口
重点是这些实现对于消费者来说是无关紧要的。另外,这个问题与 ASP.NET Web 框架无关。这确实是一个与语言/平台/框架无关的问题。无论您选择使用哪种语言来实现,答案都是相同的。
An interface decouples the consumer from the implementation details of a class. This helps enables reusability because the class implementing an interface can change, without needing to change the code consuming the implementation.
That's very confusing, maybe an example helps
Now I will write the consumer, it doesn't care how authentication is performed, it simply knows that it can authenticate users.
The code above will work regardless of the implementation of the IUserAuthentication service. This is one way to reuse code.
Now I can implement the IUserAuthentication interface
The point is that these implementations are irrelevant as far as the consumer is concerned. Also, this question is not related to ASP.NET the web framework. This is really a language/platform/framework agnostic question. The answer is the same regardless of the language you choose to implement with.
这就是开闭原则,SOLID原则的重要法则之一。
它的想法很容易改变,只需对现有代码进行最少的更改。最终有助于单元测试。
http://www.oodesign.com/design-principles.html
It is the Open and Close Principle, one of the important law of S.O.L.I.D Principles.
its idea is easy to change with minimum changes in the existing code. And ultimately helps with unit testing.
http://www.oodesign.com/design-principles.html