Listener (aka Observer)

class software_patterns.notification.Subject(*args, **kwargs)[source]

Concrete Subject which owns an important state and notifies observers.

The subject can be used to build the data encapsulating the event being broadcasted.

Both the _state and _observers attributes have a simple implementation, but can be overrode to accommodate for more complex scenarios.

The observers/subscribers are implemented as a python list. In more complex scenarios, the list of subscribers can be stored more comprehensively (categorized by event type, etc.).

The subscription management methods provided are ‘attach’, ‘detach’ (as in the SubjectInterface) and ‘add’, which attached multiple observers at once.

Example

>>> from software_patterns import Subject, Observer
>>> broadcaster = Subject()
>>> class ObserverTypeA(Observer):
...  def update(self, *args, **kwargs):
...   event = args[0].state
...   print(f'observer-type-a reacts to event {event}')
>>> class ObserverTypeB(Observer):
...  def update(self, *args, **kwargs):
...   event = args[0].state
...   print(f'observer-type-b reacts to event {event}')
>>> subscriber_1 = ObserverTypeA()
>>> subscriber_2 = ObserverTypeB()
>>> broadcaster.add(subscriber_2, subscriber_1)
>>> broadcaster.state = 'event-object-A'
>>> broadcaster.notify()
observer-type-b reacts to event event-object-A
observer-type-a reacts to event event-object-A
>>> broadcaster.detach(subscriber_2)
>>> broadcaster.state = 'event-object-B'
>>> broadcaster.notify()
observer-type-a reacts to event event-object-B
add(*observers)[source]

Subscribe multiple observers at once.

attach(observer: ObserverInterface) None[source]

Attach an observer to the subject; subscribe the observer.

detach(observer: ObserverInterface) None[source]

Detach an observer from the subject; unsubscribe the observer.

notify() None[source]

Notify all observers about an event.

property state: Optional[StateType]

Get the state of the Subject.

Returns

the object representing the current state of the Subject

Return type

StateType

class software_patterns.notification.Observer[source]
abstract update(*args, **kwargs) None

Receive an update (from a subject); handle an event notification.