单一责任原则在OOP中有效吗? [英] Does the Single Responsibility Principle work in OOP?

查看:57
本文介绍了单一责任原则在OOP中有效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力了解如何使单一责任原则"与OOP一起使用.

I am struggling to understand how the Single Responsibility Principle can me made to work with OOP.

如果我们要遵循一个三通原则,那么我们是否就不会剩下很多类,其中许多类每个可能只有一个方法?

If we are to follow the principle to a tee, then are we not left with many classes, many of which may just have one method each?

如果我们不完全遵循原则,那么原则有什么意义?

If we don't follow the principle exactly, then what is the point in the principle?

推荐答案

我喜欢这样陈述单一责任原则:您编写的所有内容-每个模块,类,接口或方法都应具有一个工作,它应该做整个工作,而只能做 个工作.

I like to state the single responsibility principle this way: "Every thing you write -- every module, class, interface, or method, should have one job. It should do the whole job and only that job.

请注意,您编写的某些东西很大(模块),有些很小(方法),有些介于中间(类),而有些大东西是由较小的东西组成的.

Notice that some of these things you write are big (modules), some are small (methods), some are in between (classes), and some of the big things are made of smaller things.

这不是问题,因为工作或职责也有各种各样的大小,并且可以按层次分解.例如,警察的工作就是保护和服务"-一项工作分解为巡逻街道",解决犯罪"等工作,每个工作都可以由不同的部门处理.这就需要进行协调(一项不同的工作),并且每个部门的工作都分解为各个人员的工作,等等.

That is not a problem, because jobs or responsibilities also come in various sizes and can be decomposed hierarchically. The job of the police force, for example, is to "protect and serve" -- one job, that decomposes into "patrol the streets", "solve crimes", etc., which can each be handled by a different unit. That creates the need for coordination (a different job), and the job of each unit breaks down into jobs for individual officers, etc.

对于每一项重要的工作,有很多方法可以将其分解为较小的工作,并且每个工作都可以通过遵循SRP和其他SOLID原则的软件设计进行建模.决定如何解决问题是软件设计艺术的重要组成部分.

For every big job, there are many ways to break it down into smaller jobs, and every one of those can be modeled by a software design that adheres to SRP and the other SOLID principles. Deciding how to break a problem down is a big part of the art of software design.

这篇关于单一责任原则在OOP中有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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