单一职责原则的一个例子是什么? [英] What is an example of the Single Responsibility Principle?

查看:28
本文介绍了单一职责原则的一个例子是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能给我举一个单一职责原则的例子?我试图理解在实践中,一个班级只有一个责任意味着什么,因为我担心我可能每天都违反这条规则.

Can someone give me an example of the Single Responsibility Principle? I am trying to understand what it means, in practice, for a class to have a single responsibility as I fear I probably break this rule daily.

推荐答案

查看 可靠的描述.

除非你要求更具体的东西,否则很难提供更多帮助.

Unless you ask for something more specific, it will be hard to help more.

单一职责是一个类做一件特定的事情(职责)而不是试图做超出它应该做的更多的概念,这也被称为高内聚力.

Single responsibility is the concept of a Class doing one specific thing (responsibility) and not trying to do more than it should, which is also referred to as High Cohesion.

类通常不会以低内聚开始,但通常在几个版本和不同的开发人员添加它们之后,您会突然注意到它变成了一些人所说的怪物或上帝类.所以这个类应该被重构.

Classes dont often start out with Low Cohesion, but typically after several releases and different developers adding onto them, suddenly you'll notice that it became a monster or God class as some call it. So the class should be refactored.

很难想出一个好的例子,但我最近能想到的一个类是我们管理不同数据包处理阶段的类,一种责任链.这个类的最初意图是维护一个阶段列表并在它们上编排调用 packetProcess().嗯,最后每个人都向这个管理器类添加了与处理阶段有关的任何东西(因为管理器类是访问阶段的一个容易的地方),尤其是阶段配置.manager 类不再有单一职责,而是还负责调用阶段以进行配置更改:因此内聚力降低了.

Its hard to think of a good example, but one I can think of recently would be a class we have that manages different packet processing stages, a type of Chain of Responsibility. The initial intention of this class was to maintain a list of stages and to orchestrate calling packetProcess() on them. Well, it ended up that everybody added anything to do with the processing stages (since the manager class was an easy place to access the stages) to this manager class, especially stage configuration. The manager class no longer had a Single Responsibility, but instead was also responsible for making calls to the stages for configuration changes: thus the Cohesion had been reduced.

我们最终不得不重构 manager 类,删除所有 stage 配置并将其放入工厂,从而让 manager 做它打算做的事情.

We ended up having to refactor the manager class, ripping out all the stage configuration and putting it in a factory, thus leaving the manager to do what it was intended to do.

这篇关于单一职责原则的一个例子是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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