gpt4 book ai didi

oop - 在 SOLID 中,SRP 和 ISP 有什么区别? (单一职责原则和接口(interface)隔离原则)

转载 作者:行者123 更新时间:2023-12-02 04:13:40 28 4
gpt4 key购买 nike

SOLID 如何“接口(interface)隔离原则”与“单一职责原则”有什么不同?

维基百科 entry for SOLID says

ISP splits interfaces which are very large into smaller and more specific ones so that clients will only have to know about the methods that are of interest to them



然而,对我来说,这听起来就像只是将 SRP 应用于接口(interface)和类。毕竟,如果一个接口(interface)只负责一个概念上的事情,那么您将无法进一步分解它。

我错过了什么,还是 ISP 与 SRP 有点多余?如果不是,那么 ISP 暗示 SRP 没有什么?

最佳答案

SRP 告诉我们,您应该在一个模块中只承担单一职责。

ISP 告诉我们,您不应该被迫面对超出您实际需要的东西。如果您想使用 print()来自接口(interface) I 的方法,您不必实例化 SwimmingPoolDriveThru为此上课。

更具体地说,直截了当,它们是对同一想法的不同看法——SRP 更关注设计者的观点,而 ISP 更关注客户端的观点.所以你基本上是对的。

这一切都来自

The ISP was first used and formulated by Robert C. Martin when doing some consulting for Xerox. Xerox had created a new printer system that could perform a variety of tasks like stapling a set of printed papers and faxing. The software for this system was created from the ground up and performed its tasks successfully. As the software grew, making modification became more and more difficult so that even the smallest change would take a redeployment cycle to an hour. This was making it near impossible to continue development. The design problem was that one main Job class was used by almost all of the tasks. Anytime a print job or a stapling job had to be done, a call was made to some method in the Job class. This resulted in a huge or 'fat' class with multitudes of methods specific to a variety of different clients. Because of this design, a staple job would know about all the methods of the print job, even though there was no use for them.



所以

The solution suggested by Martin is what is called the Interface Segregation Principle today. Applied to the Xerox software, a layer of interfaces between the Job class and all of its clients was added using the Dependency Inversion Principle. Instead of having one large Job class, a Staple Job interface or a Print Job interface was created that would be used by the Staple or Print classes, respectively, calling methods of the Job class. Therefore, one interface was created for each job, which were all implemented by the Job class.



@ http://en.wikipedia.org/wiki/Interface_segregation_principle#Origin

关于oop - 在 SOLID 中,SRP 和 ISP 有什么区别? (单一职责原则和接口(interface)隔离原则),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14388358/

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