Observer: notifying whoever is interested
An object publishes events and others subscribe to react, without the emitter knowing who they are. It is the basis of the event systems of graphical interfaces, notifications and “hooks”.
State: one behavior per state
When an object’s behavior depends on its state (an order, a traffic light, a connection), each state is a class that knows which are its next states. The valid transitions end up in a single place.
class Channel:
def __init__(self):
self._oyentes = {}
def subscribe(self, event, function):
self._oyentes.setdefault(event, []).append(function)
def publish(self, event, *args):
for function in self._oyentes.get(event, []):
function(*args)
canal = Channel()
log = []
canal.subscribe("order", lambda x: log.append(f"warehouse prepares {x}"))
canal.subscribe("order", lambda x: log.append(f"billing charges {x}"))
canal.publish("order", "A-17")
canal.publish("return", "A-17") # nobody listens: nothing happens
print(log) # ['warehouse prepares A-17', 'billing charges A-17']
# State: each state is a class that knows its transitions
class Red:
name = "red"
def next_state(self):
return Green()
class Green:
name = "green"
def next_state(self):
return Amber()
class Amber:
name = "amber"
def next_state(self):
return Red()
state = Red()
sequence = []
for _ in range(5):
sequence.append(state.name)
state = state.next_state()
print(sequence) # ['red', 'green', 'amber', 'red', 'green']
- In Observer, unsubscribing is as important as subscribing: a forgotten subscriber keeps receiving notices (and prevents the object from being freed).
- With many states, a table
{(state, action): new_state}is a compact alternative to classes. - These patterns remove conditionals scattered around the program: behavior changes by adding code, not by modifying existing code.
You practice it in Event system (Observer) and States of an order.