The observer pattern is a Behavioural Design Pattern that allows certain classes (known as observers) to subscribe to changes that happen in another class (known as the subject). The subscribing feature can be changed at runtime.
Usecase
- When you have classes that need to respond to a change in another class. More specifically, when a class has a one-waydependency on another class, and there are a lot of such dependencies.
- The dependencies could also be time-specific, such listening for a one-time event.
- This could be either a one-to-one dependency (A listens to B) to many-to-one dependency (A,B,C all listen to D).
Properties
- Subject/Publisher: The class that is being ‘observed’. It must store all the ‘subscribers’ (instances of the subscriber Interface) in an array or list (or some other data structure). Furthermore it must have an opt-in based subscribing
- Subscriber Interface: An interface that contains a public method which is called when an ‘update’ happens.
- Observer/Subscriber: Inherits from the subscriber interface. These classes ‘observe’ the subject for any changes, which is then notified via the interface method.
UML Class
classDiagram
direction LR
class Publisher {
ISubscriber[] subscribers
+subscribe(ISubscriber s)
+unsubscribe(ISubscriber s)
+NotifyAllSubscribers()
}
class ISubscriber {
+update()
}
class Subscriber
<<interface>> ISubscriber
ISubscriber <|-- Subscriber
Publisher --o ISubscriber
subscribe()
andunsubscribe()
append or delete a concreteSubscriber
from the list,subscribers
- When a change occurs,
Publisher
callsNotifyAllSubscribers()
, which iterates through the subscribers list and callsupdate()
on each item. - Every concrete subscriber handles
update()
differently
Pros vs Cons
Pros
- Dynamic subscriber allocation
- Open-Closed Principle: You can introduce new subscriber/observer classes without having to change the publisher/subject’s code
Cons
- ??? #TODO [Cons in the observer pattern]