If an application utilising the Observer design pattern has a subject class with the following responsibilities:
1) Managing and notifying observers (i.e. providing register and unregister functions and calling all observers notify functions) and
2) Its original responsibility (i.e. what ever the class was doing before it was a subject).
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?
No, the Observer design pattern does not violate the Single Responsibility Principle (SRP).
What is a responsibility?
"A responsibility denotes the obligation of an object to provide a certain behavior."
[Object-Oriented Analysis and Design, Grady Booch [et al.], page 600]
But the SRP defines a responsibility differently, as a reason to change. The SRP states that a class should have only one responsibility (reason to change).
This corresponds to the GoF principle of encapsulating things that change - a theme of many GoF design patterns. For example, the Strategy pattern encapsulates an algorithm (that can change) in a separate Strategy class.
The Observer pattern isn't about encapsulating things that change. It describes a way to define a one-to-many dependency between interacting objects without making the objects tightly coupled.
For further discussion see the GoF Design Patterns Memory for learning object-oriented design & programming at http://w3sdesign.com.
Answering my own question because although bav's answer links to a great resource it doesn't answer the question. (Although watching the video give me the understanding which allows me to answer the question!)
No, this is a misunderstanding of the Single Responsibility Principle (SRP).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With