Observer: tell everyone who asked
After this: Write a channel that tells each subscriber about an upload, follow it in a trace, and count the update calls.
On this page · 8 sections · 4 checks
Strategy and Factory were about one object: which one to hold, and which one to make. This last pattern is about many. A video channel uploads a new video. Ana and Ben want to hear about every upload. Tomorrow Cara may join, and Ben may leave. How does the channel tell everyone, without its code changing each time someone joins or leaves?
Keep a list of who asked
The idea is the one a real channel uses. Anyone who wants news asks to be added to a list. When something happens, the channel goes through the list and tells each one, the same way for all of them. Leaving means being taken off the list.
An object that has asked to be told when something happens is called an ; in this program the observers are called subscribers. The Observer pattern has four parts:
| Part | In this program |
|---|---|
| the list | subscribers, a field of Channel |
| joining and leaving | subscribe(s) adds to the end of the list; unsubscribe(s) removes |
| the event | upload(title) |
| the call to each | upload goes through the list and calls update on each subscriber |
Watch the list at work
The program below is a short version for the trace. The channel has no name, update takes only the title, and Ben is taken off the list directly instead of through an unsubscribe method. The task asks you to count the update frames that open during each upload.
- Run the programRun it and step through. Ana and Ben subscribe, in that order. Inside the first upload, watch v take each subscriber in turn, and count the frames named update that open: one per subscriber in the list. Before the second upload, line 25 takes Ben off the list (the box for ch is too short to show the whole list, so follow v); count again.
class Viewer: def __init__(self, name): self.name = name
def update(self, title): print(self.name + " got: " + title)
class Channel: def __init__(self): self.subscribers = []
def subscribe(self, v): self.subscribers.append(v)
def upload(self, title): for v in self.subscribers: v.update(title)
ch = Channel()ana = Viewer("Ana")ben = Viewer("Ben")ch.subscribe(ana)ch.subscribe(ben)ch.upload("LLD part 1")ch.subscribers.remove(ben)ch.upload("LLD part 2")run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
During the first upload the loop ran twice and called update twice: Ana, then Ben, in the order they subscribed. Ben was then removed, so the second upload called update once. The channel's code never asked who was in the list or what kind of object each one was.
The shape
The full version adds a name for the channel, an unsubscribe method, and an interface. Step through the diagram.
Press Run it to build the diagram one step at a time.
- classes
- 0
- relations
- 0
The interface, Subscriber, has one method: update(channel, title). Channel holds a list of Subscriber, and Viewer keeps that promise. The Python version has no interface class, as in lesson 2; any object with an update method can subscribe. The diagram shows the Java interface.
The code
class Viewer: def __init__(self, name): self.name = name self.inbox = []
def update(self, channel, title): self.inbox.append(title) print(f"{self.name} got: {channel} uploaded {title}")
class Channel: def __init__(self, name): self.name = name self.subscribers = []
def subscribe(self, s): self.subscribers.append(s)
def unsubscribe(self, s): self.subscribers.remove(s)
def upload(self, title): for s in self.subscribers: s.update(self.name, title)
ch = Channel("engineerhoo")ana = Viewer("Ana")ben = Viewer("Ben")ch.subscribe(ana)ch.subscribe(ben)ch.upload("LLD part 1")ch.unsubscribe(ben)ch.upload("LLD part 2")print(len(ana.inbox), len(ben.inbox))Ana got: engineerhoo uploaded LLD part 1 Ben got: engineerhoo uploaded LLD part 1 Ana got: engineerhoo uploaded LLD part 2 2 1
import java.util.ArrayList;import java.util.List;
interface Subscriber { void update(String channel, String title);}
class Viewer implements Subscriber { private final String name; final List<String> inbox = new ArrayList<>();
Viewer(String name) { this.name = name; }
public void update(String channel, String title) { inbox.add(title); System.out.println(name + " got: " + channel + " uploaded " + title); }}
class Channel { private final String name; private final List<Subscriber> subscribers = new ArrayList<>();
Channel(String name) { this.name = name; }
void subscribe(Subscriber s) { subscribers.add(s); }
void unsubscribe(Subscriber s) { subscribers.remove(s); }
void upload(String title) { for (Subscriber s : subscribers) { s.update(name, title); } }}
public class Main { public static void main(String[] args) { Channel ch = new Channel("engineerhoo"); Viewer ana = new Viewer("Ana"); Viewer ben = new Viewer("Ben"); ch.subscribe(ana); ch.subscribe(ben); ch.upload("LLD part 1"); ch.unsubscribe(ben); ch.upload("LLD part 2"); System.out.println(ana.inbox.size() + " " + ben.inbox.size()); }}Ana got: engineerhoo uploaded LLD part 1 Ben got: engineerhoo uploaded LLD part 1 Ana got: engineerhoo uploaded LLD part 2 2 1
Walk through the bottom of the program:
- Ana and Ben subscribe. The list is now Ana, Ben.
upload("LLD part 1")callsupdateon Ana, then on Ben. Each prints a line and adds the title to its inbox.- Ben unsubscribes. The list is now Ana.
upload("LLD part 2")callsupdateon Ana only.- The last line prints the size of each inbox: Ana got 2 titles, Ben got 1, so it prints
2 1.
Count the messages
The sequence diagram shows the same run. Press Run it, and count the update arrows as they appear.
Press Run it to send the messages one at a time.
- messages
- 0
There are three update arrows: two for the first upload and one for the second. The creator never talks to Ana or Ben; it only talks to the channel.
Run it
Make a third viewer, Cara, subscribe her before the second upload, and run it again. The second upload now prints two lines, and Channel did not change.
Check yourself
In the sequence diagram above, Ana and Ben subscribe, the creator uploads LLD part 1, Ben unsubscribes, and the creator uploads LLD part 2. How many update calls does the channel make in all?
These lines use Viewer and Channel from this lesson. What do they print?
# Viewer and Channel from this lesson, then:ch = Channel("engineerhoo")ana = Viewer("Ana")ben = Viewer("Ben")cara = Viewer("Cara")ch.subscribe(ben)ch.subscribe(ana)ch.upload("Trees")ch.unsubscribe(ana)ch.subscribe(cara)ch.upload("Graphs")print(len(ana.inbox), len(ben.inbox), len(cara.inbox))// Subscriber, Viewer and Channel from this lesson, then in main:Channel ch = new Channel("engineerhoo");Viewer ana = new Viewer("Ana");Viewer ben = new Viewer("Ben");Viewer cara = new Viewer("Cara");ch.subscribe(ben);ch.subscribe(ana);ch.upload("Trees");ch.unsubscribe(ana);ch.subscribe(cara);ch.upload("Graphs");System.out.println(ana.inbox.size() + " " + ben.inbox.size() + " " + cara.inbox.size());A weather station must tell a phone app, a wall screen and a logger every time the temperature changes. Next month a fourth display may be added. Which pattern fits?
Complete the line inside upload's loop, so that the channel tells each subscriber its own name and the title. The program should print the three got: lines and then 2 1.
class Viewer: def __init__(self, name): self.name = name self.inbox = []
def update(self, channel, title): self.inbox.append(title) print(f"{self.name} got: {channel} uploaded {title}")
class Channel: def __init__(self, name): self.name = name self.subscribers = []
def subscribe(self, s): self.subscribers.append(s)
def unsubscribe(self, s): self.subscribers.remove(s)
def upload(self, title): for s in self.subscribers: ________ # ← tell this subscriber
ch = Channel("engineerhoo")ana = Viewer("Ana")ben = Viewer("Ben")ch.subscribe(ana)ch.subscribe(ben)ch.upload("LLD part 1")ch.unsubscribe(ben)ch.upload("LLD part 2")print(len(ana.inbox), len(ben.inbox))import java.util.ArrayList;import java.util.List;
interface Subscriber { void update(String channel, String title);}
class Viewer implements Subscriber { private final String name; final List<String> inbox = new ArrayList<>();
Viewer(String name) { this.name = name; }
public void update(String channel, String title) { inbox.add(title); System.out.println(name + " got: " + channel + " uploaded " + title); }}
class Channel { private final String name; private final List<Subscriber> subscribers = new ArrayList<>();
Channel(String name) { this.name = name; }
void subscribe(Subscriber s) { subscribers.add(s); }
void unsubscribe(Subscriber s) { subscribers.remove(s); }
void upload(String title) { for (Subscriber s : subscribers) { ________ // ← tell this subscriber } }}
public class Main { public static void main(String[] args) { Channel ch = new Channel("engineerhoo"); Viewer ana = new Viewer("Ana"); Viewer ben = new Viewer("Ben"); ch.subscribe(ana); ch.subscribe(ben); ch.upload("LLD part 1"); ch.unsubscribe(ben); ch.upload("LLD part 2"); System.out.println(ana.inbox.size() + " " + ben.inbox.size()); }}Honesty notes
- Spot the problem Observer solves: several objects want to hear when something happens, and they come and go.
- Write a channel that keeps a list of subscribers, with subscribe, unsubscribe and an upload that calls update on each.
- Follow an upload in a trace: one update call per subscriber, in the order they subscribed.
- Count the update messages in a sequence diagram, and say what changes after an unsubscribe.
- Name the pitfalls: a subscriber never removed stays in the list, a slow one slows every upload, and order follows subscribing.