In SOLID, what is the distinction between SRP and ISP? (Single Responsibility Principle and Interface Segregation Principle)

前端 未结 4 1684
情歌与酒
情歌与酒 2021-02-02 06:05

How does the SOLID \"Interface Segregation Principle\" differ from \"Single Responsibility Principle\"?

The Wikipedia entry for SOLID says that

IS

4条回答
  •  猫巷女王i
    2021-02-02 06:12

    SRP tells us that you should only have a single responsibility in a module.

    ISP tells us that you should not be forced to be confronted with more than you actually need. If you want to use a print() method from interface I, you shouldn't have to instantiate a SwimmingPool or a DriveThru class for that.

    More concretely, and going straight to the point, they are different views on the same idea -- SRP is more focused on the designer-side point-of-view, while ISP is more focused on the client-side point-of-view. So you're basically right.

    It all came from

    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.

    so

    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

提交回复
热议问题