观察者模式是否违反单一责任原则? [英] Does the Observer pattern violate single responsibiliy principle?

查看:127
本文介绍了观察者模式是否违反单一责任原则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果使用观察者设计模式的应用程序具有主题类,其职责如下:

If an application utilising the Observer design pattern has a subject class with the following responsibilities:

1)管理和通知观察者(即提供注册和注销功能并调用所有观察者的通知函数)和

1) Managing and notifying observers (i.e. providing register and unregister functions and calling all observers notify functions) and

2)其原始职责(即该类之前所做的一切)一个主题)。

2) Its original responsibility (i.e. what ever the class was doing before it was a subject).

此类是否违反单一责任原则?它显然有多个职责,但是读了SRP后,我感到困惑,更改的原因是在设计时还是在运行时更改?

Does this class violate the Single Responsibility Principle? It clearly has more than one responsibility but reading up on the SRP I am confused wrt 'reason for change' is this change at design time or run time?

推荐答案

回答我自己的问题,因为尽管bav的答案链接到大量资源,但却无法回答问题。 (尽管观看视频可以使我理解,让我可以回答问题!)

不,这是对单一责任原则(SRP)的误解)。

No, this is a misunderstanding of the Single Responsibility Principle (SRP).

SRP中的职责是指可能发起更改请求的客户角色
例如,如果类 Employee 具有 calculatePay() displayEmployee( )方法可以合理地认为它违反了SRP,因为 calculatePay 将属于公司会计师,而 displayEmployee 属于报告文员。这意味着两个角色不同的人可以请求更改班级。

The responsibility in SRP refers to a customer role who may initiate a change request. For example if a class Employee has the calculatePay() and displayEmployee() methods it could reasonably be assumed to violate SRP as calculatePay would 'belong' to the company accountant where as displayEmployee would belong to the reports clerk. This would mean two people with separate roles could request changes to a class.

观察者模式不会添加新的责任(至少不是SRP责任),因为没有客户角色会关心此类会向观察者发布更改。

The observer pattern does not add a new responsibility (as least not an SRP responsibility) as no customer role would care that this class publishes changes to its observers.

这篇关于观察者模式是否违反单一责任原则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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