Observer API Documentation

class Observer(*args, **kwargs)[source]

Bases: Protocol

Interface for observers that listen for updates from a subject.

update(state)[source]

Called by the subject to notify the observer of a state change.

Parameters:

state (str) – The updated state.

Return type:

None

class Subject[source]

Bases: object

Manages observers and notifies them of state changes.

__init__()[source]

Initialize the Subject with an empty list of observers and a default state.

attach(observer)[source]

Add an observer to the subject.

Parameters:

observer (Observer) – The observer to attach.

Return type:

None

detach(observer)[source]

Remove an observer from the subject.

Parameters:

observer (Observer) – The observer to detach.

Return type:

None

notify()[source]

Notify all attached observers of the current state.

Return type:

None

set_state(state)[source]

Update the subject’s state and notify observers.

Parameters:

state (str) – The new state to set.

Return type:

None

get_state()[source]

Retrieve the current state of the subject.

Return type:

str

Returns:

The current state.

class ConcreteObserver(name)[source]

Bases: object

Concrete implementation of an observer.

Parameters:

name (str)

__init__(name)[source]

Initialize the concrete observer with a given name.

Parameters:

name (str) – The name of the observer.

update(state)[source]

Receive an update from the subject.

Parameters:

state (str) – The updated state.

Return type:

None