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

查看:15
本文介绍了单一职责原则在 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天全站免登陆