Observer: Tell Whoever's Listening
When the code that places an order has to call the kitchen screen, the customer's text and next month the delivery app by name, it grows with every new listener; the Observer pattern lets the order keep a list of whoever wants to know, and tell each of them, without knowing who they are.
Apprentice · OOP · Updated
After this lesson you can
- Let an object tell a list of listeners about a change, without knowing who they are
- Spot the smells that point to Observer: one method that calls everyone who cares, growing with each new one
Key takeaways
- The smell: one method that calls everyone who cares about a change, and grows by one line for each new one.
- The cause: the thing that changes knows each listener by name, so it has to change whenever the list of listeners does.
- The fix: the order desk keeps a list of listeners; anyone can subscribe, and placing an order tells each one.
- A listener can be an object with an agreed method (the classic version) or a function (the modern one).
Before this: Meet the Bakery App, interfaces (a promise any class can keep), and passing a function as a value.
The owner's third wish: tell the kitchen about new orders. When a customer orders at the counter, the order has to show on the kitchen's screen, and the customer gets a text. Next month, a delivery service starts, and its drivers' app needs to hear about every order too. Every new "someone who wants to know" means another change, and that's the problem this lesson solves, with a pattern called Observer.
The symptom: placing an order calls everyone by name
Here is the order desk this month, with the delivery app newly added:
new OrderDesk().Place(new List<IProduct> { new Cake(), new Cupcakes(), new CookieBox() });
class OrderDesk
{
private readonly KitchenScreen kitchen = new KitchenScreen();
private readonly CustomerText text = new CustomerText();
private readonly DeliveryApp delivery = new DeliveryApp(); // added this month
public void Place(List<IProduct> products)
{
kitchen.Show(products);
text.Send(products);
delivery.PickUp(products); // added this month
}
}
class KitchenScreen
{
public void Show(List<IProduct> products) => Console.WriteLine( quot;Kitchen screen: {products.Count} items to bake");
}
class CustomerText
{
public void Send(List<IProduct> products) => Console.WriteLine( quot;Text to customer: we got your ${products.Sum(product => product.Price)} order");
}
class DeliveryApp
{
public void PickUp(List<IProduct> products) => Console.WriteLine( quot;Delivery app: a ${products.Sum(product => product.Price)} order to deliver");
}
interface IProduct
{
string Name { get; }
int Price { get; }
}
class Cake : IProduct { public string Name => "Cake"; public int Price => 30; }
class Cupcakes : IProduct { public string Name => "Cupcakes"; public int Price => 12; }
class CookieBox : IProduct { public string Name => "Cookie box"; public int Price => 8; }
Kitchen screen: 3 items to bake
Text to customer: we got your $50 order
Delivery app: a $50 order to deliver
interface Product {
String name();
int price();
}
class Cake implements Product { public String name() { return "Cake"; } public int price() { return 30; } }
class Cupcakes implements Product { public String name() { return "Cupcakes"; } public int price() { return 12; } }
class CookieBox implements Product { public String name() { return "Cookie box"; } public int price() { return 8; } }
static int total(List<Product> products) {
int total = 0;
for (Product product : products) { total += product.price(); }
return total;
}
class KitchenScreen {
void show(List<Product> products) { IO.println("Kitchen screen: " + products.size() + " items to bake"); }
}
class CustomerText {
void send(List<Product> products) { IO.println("Text to customer: we got your quot; + total(products) + " order"); }
}
class DeliveryApp {
void pickUp(List<Product> products) { IO.println("Delivery app: a quot; + total(products) + " order to deliver"); }
}
class OrderDesk {
KitchenScreen kitchen = new KitchenScreen();
CustomerText text = new CustomerText();
DeliveryApp delivery = new DeliveryApp(); // added this month
void place(List<Product> products) {
kitchen.show(products);
text.send(products);
delivery.pickUp(products); // added this month
}
}
void main() {
new OrderDesk().place(List.of(new Cake(), new Cupcakes(), new CookieBox()));
}
Kitchen screen: 3 items to bake
Text to customer: we got your $50 order
Delivery app: a $50 order to deliver
class Cake:
name = "Cake"
price = 30
class Cupcakes:
name = "Cupcakes"
price = 12
class CookieBox:
name = "Cookie box"
price = 8
def total(products):
return sum(product.price for product in products)
class KitchenScreen:
def show(self, products):
print(f"Kitchen screen: {len(products)} items to bake")
class CustomerText:
def send(self, products):
print(f"Text to customer: we got your ${total(products)} order")
class DeliveryApp:
def pick_up(self, products):
print(f"Delivery app: a ${total(products)} order to deliver")
class OrderDesk:
def __init__(self):
self.kitchen = KitchenScreen()
self.text = CustomerText()
self.delivery = DeliveryApp() # added this month
def place(self, products):
self.kitchen.show(products)
self.text.send(products)
self.delivery.pick_up(products) # added this month
OrderDesk().place([Cake(), Cupcakes(), CookieBox()])
Kitchen screen: 3 items to bake
Text to customer: we got your $50 order
Delivery app: a $50 order to deliver
class Cake { name = "Cake"; price = 30; }
class Cupcakes { name = "Cupcakes"; price = 12; }
class CookieBox { name = "Cookie box"; price = 8; }
function total(products) {
return products.reduce((sum, product) => sum + product.price, 0);
}
class KitchenScreen {
show(products) { console.log(`Kitchen screen: ${products.length} items to bake`); }
}
class CustomerText {
send(products) { console.log(`Text to customer: we got your ${total(products)} order`); }
}
class DeliveryApp {
pickUp(products) { console.log(`Delivery app: a ${total(products)} order to deliver`); }
}
class OrderDesk {
kitchen = new KitchenScreen();
text = new CustomerText();
delivery = new DeliveryApp(); // added this month
place(products) {
this.kitchen.show(products);
this.text.send(products);
this.delivery.pickUp(products); // added this month
}
}
new OrderDesk().place([new Cake(), new Cupcakes(), new CookieBox()]);
Kitchen screen: 3 items to bake
Text to customer: we got your $50 order
Delivery app: a $50 order to deliver
interface Product {
name: string;
price: number;
}
class Cake implements Product { name = "Cake"; price = 30; }
class Cupcakes implements Product { name = "Cupcakes"; price = 12; }
class CookieBox implements Product { name = "Cookie box"; price = 8; }
function total(products: Product[]): number {
return products.reduce((sum, product) => sum + product.price, 0);
}
class KitchenScreen {
show(products: Product[]): void { console.log(`Kitchen screen: ${products.length} items to bake`); }
}
class CustomerText {
send(products: Product[]): void { console.log(`Text to customer: we got your ${total(products)} order`); }
}
class DeliveryApp {
pickUp(products: Product[]): void { console.log(`Delivery app: a ${total(products)} order to deliver`); }
}
class OrderDesk {
kitchen = new KitchenScreen();
text = new CustomerText();
delivery = new DeliveryApp(); // added this month
place(products: Product[]): void {
this.kitchen.show(products);
this.text.send(products);
this.delivery.pickUp(products); // added this month
}
}
new OrderDesk().place([new Cake(), new Cupcakes(), new CookieBox()]);
Kitchen screen: 3 items to bake
Text to customer: we got your $50 order
Delivery app: a $50 order to deliver
It works, and every month it changes again. The order desk had to learn about the delivery app: a new field, a new line, a new method name to remember. A loyalty-points screen next spring means the same edits again. And you can't test placing an order without a real kitchen screen and a real text service, because the desk makes them itself.
- The symptom: one method that calls everyone who cares about a change, by name, and grows by one line for each new one.
- The cause: the order desk knows each listener personally. Code that knows too much about other code is tightly coupled: a change to the list of listeners forces a change to the desk.
What would you try?
One big TellEveryone(order) function. The same calls, moved somewhere else. It still grows with every new listener.
A flag for each listener: sendText = true, notifyDelivery = true. Now the desk knows every listener and every flag.
Let the delivery app check for new orders every minute. It works, but it's always up to a minute late, and every new listener adds more checking.
What we want is for the desk to say "an order was placed!" once, and for anyone who cares to hear it, without the desk knowing who they are.
The fix: a list of whoever's listening
Online stores do this when an item is sold out. You tap "text me when it's back in stock", and your number goes on a list. When the item comes back, the store sends one message to everyone on the list. It doesn't know or care who you are, and anyone can sign up.

The order desk works the same way. It keeps a list of listeners. Anyone who wants to hear about new orders subscribes: they're added to the list. Placing an order goes down the list and tells each one. The desk only knows the promise every listener keeps: "you can tell me an order was placed."

The classic version: listeners keep a promise
Each listener keeps one promise, OrderListener: it has an orderPlaced method. The desk keeps a list of them:
OrderDesk desk = new OrderDesk();
desk.Subscribe(new KitchenScreen());
desk.Subscribe(new CustomerText());
desk.Subscribe(new DeliveryApp()); // next month: one line, and the desk doesn't change
desk.Place(new List<IProduct> { new Cake(), new Cupcakes(), new CookieBox() });
interface IOrderListener
{
void OrderPlaced(List<IProduct> products);
}
class OrderDesk
{
private readonly List<IOrderListener> listeners = new List<IOrderListener>();
public void Subscribe(IOrderListener listener) => listeners.Add(listener);
public void Place(List<IProduct> products)
{
foreach (IOrderListener listener in listeners)
{
listener.OrderPlaced(products);
}
}
}
class KitchenScreen : IOrderListener
{
public void OrderPlaced(List<IProduct> products) => Console.WriteLine( quot;Kitchen screen: {products.Count} items to bake");
}
class CustomerText : IOrderListener
{
public void OrderPlaced(List<IProduct> products) => Console.WriteLine( quot;Text to customer: we got your ${products.Sum(product => product.Price)} order");
}
class DeliveryApp : IOrderListener
{
public void OrderPlaced(List<IProduct> products) => Console.WriteLine( quot;Delivery app: a ${products.Sum(product => product.Price)} order to deliver");
}
interface IProduct
{
string Name { get; }
int Price { get; }
}
class Cake : IProduct { public string Name => "Cake"; public int Price => 30; }
class Cupcakes : IProduct { public string Name => "Cupcakes"; public int Price => 12; }
class CookieBox : IProduct { public string Name => "Cookie box"; public int Price => 8; }
Kitchen screen: 3 items to bake
Text to customer: we got your $50 order
Delivery app: a $50 order to deliver
interface Product {
String name();
int price();
}
class Cake implements Product { public String name() { return "Cake"; } public int price() { return 30; } }
class Cupcakes implements Product { public String name() { return "Cupcakes"; } public int price() { return 12; } }
class CookieBox implements Product { public String name() { return "Cookie box"; } public int price() { return 8; } }
static int total(List<Product> products) {
int total = 0;
for (Product product : products) { total += product.price(); }
return total;
}
interface OrderListener {
void orderPlaced(List<Product> products);
}
class OrderDesk {
private final List<OrderListener> listeners = new ArrayList<>();
void subscribe(OrderListener listener) { listeners.add(listener); }
void place(List<Product> products) {
for (OrderListener listener : listeners) {
listener.orderPlaced(products);
}
}
}
class KitchenScreen implements OrderListener {
public void orderPlaced(List<Product> products) { IO.println("Kitchen screen: " + products.size() + " items to bake"); }
}
class CustomerText implements OrderListener {
public void orderPlaced(List<Product> products) { IO.println("Text to customer: we got your quot; + total(products) + " order"); }
}
class DeliveryApp implements OrderListener {
public void orderPlaced(List<Product> products) { IO.println("Delivery app: a quot; + total(products) + " order to deliver"); }
}
void main() {
OrderDesk desk = new OrderDesk();
desk.subscribe(new KitchenScreen());
desk.subscribe(new CustomerText());
desk.subscribe(new DeliveryApp()); // next month: one line, and the desk doesn't change
desk.place(List.of(new Cake(), new Cupcakes(), new CookieBox()));
}
Kitchen screen: 3 items to bake
Text to customer: we got your $50 order
Delivery app: a $50 order to deliver
class Cake:
name = "Cake"
price = 30
class Cupcakes:
name = "Cupcakes"
price = 12
class CookieBox:
name = "Cookie box"
price = 8
def total(products):
return sum(product.price for product in products)
class OrderDesk:
def __init__(self):
self.listeners = []
def subscribe(self, listener):
self.listeners.append(listener)
def place(self, products):
for listener in self.listeners:
listener.order_placed(products)
# Every listener keeps the same promise: it has an order_placed method.
class KitchenScreen:
def order_placed(self, products):
print(f"Kitchen screen: {len(products)} items to bake")
class CustomerText:
def order_placed(self, products):
print(f"Text to customer: we got your ${total(products)} order")
class DeliveryApp:
def order_placed(self, products):
print(f"Delivery app: a ${total(products)} order to deliver")
desk = OrderDesk()
desk.subscribe(KitchenScreen())
desk.subscribe(CustomerText())
desk.subscribe(DeliveryApp()) # next month: one line, and the desk doesn't change
desk.place([Cake(), Cupcakes(), CookieBox()])
Kitchen screen: 3 items to bake
Text to customer: we got your $50 order
Delivery app: a $50 order to deliver
class Cake { name = "Cake"; price = 30; }
class Cupcakes { name = "Cupcakes"; price = 12; }
class CookieBox { name = "Cookie box"; price = 8; }
function total(products) {
return products.reduce((sum, product) => sum + product.price, 0);
}
class OrderDesk {
#listeners = [];
subscribe(listener) { this.#listeners.push(listener); }
place(products) {
for (const listener of this.#listeners) {
listener.orderPlaced(products);
}
}
}
// Every listener keeps the same promise: it has an orderPlaced method.
class KitchenScreen {
orderPlaced(products) { console.log(`Kitchen screen: ${products.length} items to bake`); }
}
class CustomerText {
orderPlaced(products) { console.log(`Text to customer: we got your ${total(products)} order`); }
}
class DeliveryApp {
orderPlaced(products) { console.log(`Delivery app: a ${total(products)} order to deliver`); }
}
const desk = new OrderDesk();
desk.subscribe(new KitchenScreen());
desk.subscribe(new CustomerText());
desk.subscribe(new DeliveryApp()); // next month: one line, and the desk doesn't change
desk.place([new Cake(), new Cupcakes(), new CookieBox()]);
Kitchen screen: 3 items to bake
Text to customer: we got your $50 order
Delivery app: a $50 order to deliver
interface Product {
name: string;
price: number;
}
class Cake implements Product { name = "Cake"; price = 30; }
class Cupcakes implements Product { name = "Cupcakes"; price = 12; }
class CookieBox implements Product { name = "Cookie box"; price = 8; }
function total(products: Product[]): number {
return products.reduce((sum, product) => sum + product.price, 0);
}
interface OrderListener {
orderPlaced(products: Product[]): void;
}
class OrderDesk {
#listeners: OrderListener[] = [];
subscribe(listener: OrderListener): void { this.#listeners.push(listener); }
place(products: Product[]): void {
for (const listener of this.#listeners) {
listener.orderPlaced(products);
}
}
}
class KitchenScreen implements OrderListener {
orderPlaced(products: Product[]): void { console.log(`Kitchen screen: ${products.length} items to bake`); }
}
class CustomerText implements OrderListener {
orderPlaced(products: Product[]): void { console.log(`Text to customer: we got your ${total(products)} order`); }
}
class DeliveryApp implements OrderListener {
orderPlaced(products: Product[]): void { console.log(`Delivery app: a ${total(products)} order to deliver`); }
}
const desk = new OrderDesk();
desk.subscribe(new KitchenScreen());
desk.subscribe(new CustomerText());
desk.subscribe(new DeliveryApp()); // next month: one line, and the desk doesn't change
desk.place([new Cake(), new Cupcakes(), new CookieBox()]);
Kitchen screen: 3 items to bake
Text to customer: we got your $50 order
Delivery app: a $50 order to deliver
The modern version: listeners are functions
A listener with one method is really one function. So the list can hold functions, and subscribing is handing one in:
OrderDesk desk = new OrderDesk();
desk.Subscribe(products => Console.WriteLine( quot;Kitchen screen: {products.Count} items to bake"));
desk.Subscribe(products => Console.WriteLine( quot;Text to customer: we got your ${products.Sum(product => product.Price)} order"));
desk.Subscribe(products => Console.WriteLine( quot;Delivery app: a ${products.Sum(product => product.Price)} order to deliver"));
desk.Place(new List<IProduct> { new Cake(), new Cupcakes(), new CookieBox() });
class OrderDesk
{
private readonly List<Action<List<IProduct>>> listeners = new List<Action<List<IProduct>>>();
public void Subscribe(Action<List<IProduct>> listener) => listeners.Add(listener);
public void Place(List<IProduct> products)
{
foreach (Action<List<IProduct>> listener in listeners)
{
listener(products);
}
}
}
interface IProduct
{
string Name { get; }
int Price { get; }
}
class Cake : IProduct { public string Name => "Cake"; public int Price => 30; }
class Cupcakes : IProduct { public string Name => "Cupcakes"; public int Price => 12; }
class CookieBox : IProduct { public string Name => "Cookie box"; public int Price => 8; }
Kitchen screen: 3 items to bake
Text to customer: we got your $50 order
Delivery app: a $50 order to deliver
interface Product {
String name();
int price();
}
class Cake implements Product { public String name() { return "Cake"; } public int price() { return 30; } }
class Cupcakes implements Product { public String name() { return "Cupcakes"; } public int price() { return 12; } }
class CookieBox implements Product { public String name() { return "Cookie box"; } public int price() { return 8; } }
static int total(List<Product> products) {
int total = 0;
for (Product product : products) { total += product.price(); }
return total;
}
class OrderDesk {
private final List<Consumer<List<Product>>> listeners = new ArrayList<>();
void subscribe(Consumer<List<Product>> listener) { listeners.add(listener); }
void place(List<Product> products) {
for (Consumer<List<Product>> listener : listeners) {
listener.accept(products);
}
}
}
void main() {
OrderDesk desk = new OrderDesk();
desk.subscribe(products -> IO.println("Kitchen screen: " + products.size() + " items to bake"));
desk.subscribe(products -> IO.println("Text to customer: we got your quot; + total(products) + " order"));
desk.subscribe(products -> IO.println("Delivery app: a quot; + total(products) + " order to deliver"));
desk.place(List.of(new Cake(), new Cupcakes(), new CookieBox()));
}
Kitchen screen: 3 items to bake
Text to customer: we got your $50 order
Delivery app: a $50 order to deliver
class Cake:
name = "Cake"
price = 30
class Cupcakes:
name = "Cupcakes"
price = 12
class CookieBox:
name = "Cookie box"
price = 8
def total(products):
return sum(product.price for product in products)
class OrderDesk:
def __init__(self):
self.listeners = []
def subscribe(self, listener):
self.listeners.append(listener)
def place(self, products):
for listener in self.listeners:
listener(products)
desk = OrderDesk()
desk.subscribe(lambda products: print(f"Kitchen screen: {len(products)} items to bake"))
desk.subscribe(lambda products: print(f"Text to customer: we got your ${total(products)} order"))
desk.subscribe(lambda products: print(f"Delivery app: a ${total(products)} order to deliver"))
desk.place([Cake(), Cupcakes(), CookieBox()])
Kitchen screen: 3 items to bake
Text to customer: we got your $50 order
Delivery app: a $50 order to deliver
class Cake { name = "Cake"; price = 30; }
class Cupcakes { name = "Cupcakes"; price = 12; }
class CookieBox { name = "Cookie box"; price = 8; }
function total(products) {
return products.reduce((sum, product) => sum + product.price, 0);
}
class OrderDesk {
#listeners = [];
subscribe(listener) { this.#listeners.push(listener); }
place(products) {
for (const listener of this.#listeners) {
listener(products);
}
}
}
const desk = new OrderDesk();
desk.subscribe((products) => console.log(`Kitchen screen: ${products.length} items to bake`));
desk.subscribe((products) => console.log(`Text to customer: we got your ${total(products)} order`));
desk.subscribe((products) => console.log(`Delivery app: a ${total(products)} order to deliver`));
desk.place([new Cake(), new Cupcakes(), new CookieBox()]);
Kitchen screen: 3 items to bake
Text to customer: we got your $50 order
Delivery app: a $50 order to deliver
interface Product {
name: string;
price: number;
}
class Cake implements Product { name = "Cake"; price = 30; }
class Cupcakes implements Product { name = "Cupcakes"; price = 12; }
class CookieBox implements Product { name = "Cookie box"; price = 8; }
function total(products: Product[]): number {
return products.reduce((sum, product) => sum + product.price, 0);
}
type OrderListener = (products: Product[]) => void;
class OrderDesk {
#listeners: OrderListener[] = [];
subscribe(listener: OrderListener): void { this.#listeners.push(listener); }
place(products: Product[]): void {
for (const listener of this.#listeners) {
listener(products);
}
}
}
const desk = new OrderDesk();
desk.subscribe((products) => console.log(`Kitchen screen: ${products.length} items to bake`));
desk.subscribe((products) => console.log(`Text to customer: we got your ${total(products)} order`));
desk.subscribe((products) => console.log(`Delivery app: a ${total(products)} order to deliver`));
desk.place([new Cake(), new Cupcakes(), new CookieBox()]);
Kitchen screen: 3 items to bake
Text to customer: we got your $50 order
Delivery app: a $50 order to deliver
All three versions print the same lines. In both fixes, the desk is finished: it never learns another listener's name. The delivery app, the loyalty-points screen next spring, and a test that records what it heard are each one subscribe call, made from outside the desk.
How it got its name
The order desk is being observed: watched for changes. The kitchen screen and the others are its observers, also called listeners or subscribers. Teams found this fix so often, in every app with screens that update themselves, that it's one of the best-known patterns: Observer. Pass 3 comes back to it, with the events built into each language and with observers on other computers.
Where you've already used it
button.addEventListener("click", ...)in a browser: the button is observed, and your function is the observer.- C#'s
button.Click += OnClickand Java'sbutton.addActionListener(...)are the same idea in desktop apps. - A spreadsheet cell that updates when a cell it uses changes is an observer of that cell.
When not to use it
- When there's exactly one listener, and there always will be. A direct call is easier to read: you can see who's called.
- When the order matters and listeners depend on each other, such as "charge the card, then print the receipt". A list of listeners doesn't promise order between them; checkout steps that must happen in sequence belong together (the next lesson).
- When you need an answer back. Observers are told; they don't reply.
The cost: reading the desk's code no longer tells you who's listening, so you look at where things subscribe. And a listener that's no longer needed has to be removed from the list, or it keeps hearing everything; Pass 3 covers unsubscribing.
How often you'll meet it: every day (our estimate: every click handler is one).
Check yourself
2 questions to try on the lesson page.
So what
When one method keeps growing a line for every "someone who wants to know", let them subscribe instead. The thing that changes says "it happened" once, and the list decides who hears.