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

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

问题描述

有人可以给我一个单一责任原则"的例子吗?我正试图了解在实践中,让一个班级承担单一责任是什么意思,因为我担心自己每天可能会违反此规则.

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.

很难想到一个很好的例子,但是我最近想到的是我们管理不同的数据包处理阶段的一类,类型为Chain of Responsibility.该类的最初目的是维护一个阶段列表,并在其上协调调用packetProcess().嗯,最终,每个人​​都向该管理器类添加了与处理阶段有关的任何内容(因为管理器类是访问这些阶段的简便位置),尤其是阶段配置.经理级不再具有单一职责,而是还负责对配置更改的各个阶段进行调用:因此降低了内聚性.

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.

我们最终不得不重构经理类,删除所有阶段配置并将其放置在工厂中,从而让经理去做打算做的事情.

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天全站免登陆