Observer Pattern in Python
Level 5534 keystrokes
This implements the Observer pattern. Subject notifies all attached observers when its state changes.
Python code
# Subject is the class being observed# Maintains list of observers and notifies them of changes1class Subject: # __init__ sets up observer list and initial state2 def __init__(self): # List to hold observer references3 self._observers: list = [] # State that observers are interested in4 self._state: int = 05 # attach adds an observer to be notified # observer must have update() method6 def attach(self, observer): # Add observer to the list7 self._observers.append(observer)8 # set_state changes state and notifies observers # state is the new value to set9 def set_state(self, state: int): # Update internal state10 self._state = state # Notify all observers of the change11 self._notify()12 # _notify is internal by convention (leading underscore) # Called automatically when state changes13 def _notify(self): # Loop through all registered observers14 for observer in self._observers: # Call each observer's update with new state15 observer.update(self._state)16 # Observer receives notifications from Subject# Each observer has a name for identification17class Observer: # __init__ takes name to identify this observer18 def __init__(self, name: str):19 self.name = name20 # update is called by Subject when state changes # state is the new state value21 def update(self, state: int): # Print notification with observer name and new state22 print(f"{self.name} received: {state}")23 # Create Subject to be observed24subject = Subject()# Attach Observer named "A"25subject.attach(Observer("A"))# Attach Observer named "B"26subject.attach(Observer("B"))# Set state to 42, triggering notifications# Both A and B will receive the update27subject.set_state(42)Output
A received: 42 B received: 42
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
_× 18(× 16)× 16:× 15.× 14"× 6=× 5,× 4{× 2}× 2