Observer
In short: Observer lets one object notify a list of subscribers when something happens, without knowing who they are or what they do.
Problem
The payment that calls everyone
A customer pays order #1042 for €80. After that, a receipt has to go out by email and SMS, the warehouse has to reserve the goods, and accounting has to issue an invoice. The payments class does it all itself:
class Payments { private final EmailService email = new EmailService(); private final SmsService sms = new SmsService(); private final Warehouse warehouse = new Warehouse(); private final InvoiceService invoices = new InvoiceService();
public void markPaid(Order order) { email.sendReceipt(order); sms.notifyPaid(order); warehouse.reserve(order); invoices.issue(order); }}Each service is a small class that prints what it did:
Payments payments = new Payments();payments.markPaid(new Order(1042, 80));Email: receipt for #1042SMS: order #1042 is paidWarehouse: reserve #1042Invoice: €80.00 for #1042It works. But marketing wants loyalty points on every payment. That is one more field and one more line in markPaid. Tomorrow comes a push notification, the day after, statistics. The code every payment goes through is touched for things that have nothing to do with the payment.
Worse, today the SMS gateway is not responding:
class SmsService { public void notifyPaid(Order order) { throw new IllegalStateException("SMS gateway is not responding"); }}Payments payments = new Payments();try { payments.markPaid(new Order(1042, 80));} catch (IllegalStateException e) { System.out.println("Payment failed: " + e.getMessage());}Email: receipt for #1042Payment failed: SMS gateway is not respondingThe money is taken, and the page tells the customer the payment failed. The warehouse reserved nothing, there is no invoice. One service nobody thinks is important stopped the whole payment.
The idea
Observer: whoever wants to know subscribes
The payments shouldn't know who cares about them. They should only know that someone wants to find out when an order is paid.
So the payments keep a list of subscribers. Every subscriber has the same shape: an interface with one method that takes the order. Whoever wants to know subscribes from outside. On a payment, the object walks the list and calls every subscriber with the order.This is the Observer pattern. It has three roles:
- the subject is where something happens. Here it is the payments. Books also call it the publisher;
- the subscribers (observers) want to find out. They are email, SMS, the warehouse;
- the notification is the walk through the list: every subscriber is given what happened, here the paid order.
A new subscriber is new code outside. The subject is not touched. A subscriber can also unsubscribe, and then it doesn't hear any more.
See it
The subscribers find out on their own
PaidListener. The payments keep a list of them:record Order(int id, double total) {}
interface PaidListener { void paid(Order order);}
class Payments { private final List<PaidListener> listeners = new ArrayList<>();
public void subscribe(PaidListener listener) { listeners.add(listener); }
public void unsubscribe(PaidListener listener) { listeners.remove(listener); }
public void markPaid(Order order) { for (PaidListener listener : listeners) { listener.paid(order); } }}PaidListener has one method, so every subscriber can be a lambda:PaidListener email = order -> System.out.println("Email: receipt for #" + order.id());PaidListener sms = order -> System.out.println("SMS: order #" + order.id() + " is paid");PaidListener warehouse = order -> System.out.println("Warehouse: reserve #" + order.id());PaidListener loyalty = order -> System.out.println("Points: +" + (int) order.total() + " for #" + order.id());Three subscribers, a payment. Then loyalty points arrive, and the customer turns SMS off:
Payments payments = new Payments();payments.subscribe(email);payments.subscribe(sms);payments.subscribe(warehouse);payments.markPaid(new Order(1042, 80));
payments.subscribe(loyalty);payments.unsubscribe(sms);payments.markPaid(new Order(1043, 25));Email: receipt for #1042SMS: order #1042 is paidWarehouse: reserve #1042Email: receipt for #1043Warehouse: reserve #1043Points: +25 for #1043Payments payments = new Payments();payments.subscribe(email);payments.subscribe(sms);payments.subscribe(warehouse);payments.markPaid(new Order(1042, 80));
payments.subscribe(loyalty);payments.unsubscribe(sms);payments.markPaid(new Order(1043, 25));Step by step, in words
- Payments starts with an empty listeners list.
- email subscribes: it goes into the listeners list.
- sms and warehouse too. Payments doesn't know who they are, only that they take an order.
- Order #1042 is paid. The notification goes out to every subscriber, in the order they subscribed.
- One after another, in the same call: receipt, SMS, reservation. Each subscriber does its own job.
- Loyalty points arrive: loyalty subscribes from outside. Not a single line of Payments changes.
- The customer turns SMS off: sms unsubscribes and leaves the list.
- Order #1043: the notification reaches email, warehouse and loyalty. sms is not on the list any more and hears nothing.
Payments is the same code from start to end. The points appeared without a single line of it changing, and the SMS stopped without the payments noticing.
More precisely, if you are curious
- A subscriber can also be a method reference:
payments.subscribe(mailer::sendReceipt). But everymailer::sendReceiptmakes a new object.unsubscribewith a new::doesn't find the old one in the list and removes nothing:
Payments payments = new Payments();EmailService mailer = new EmailService();payments.subscribe(mailer::sendReceipt);payments.unsubscribe(mailer::sendReceipt);payments.markPaid(new Order(1042, 80));Email: receipt for #1042So a subscriber you will unsubscribe is kept in a variable, like sms above.
- Subscribers are called one after another, in the same call to
markPaid. A slow SMS gateway slows down the payment too. Big shops send the event to a queue (a message broker), and the services pick it up from there when they are ready.
See it
One subscriber fails, the others shouldn't
Observer removed the link between the payment and the SMS, but not the error. The SMS subscriber throws:
PaidListener sms = order -> { throw new IllegalStateException("SMS gateway is not responding");};Payments payments = new Payments();payments.subscribe(email);payments.subscribe(sms);payments.subscribe(warehouse);try { payments.markPaid(new Order(1042, 80));} catch (IllegalStateException e) { System.out.println("Payment failed: " + e.getMessage());}Email: receipt for #1042Payment failed: SMS gateway is not respondingSubscribers are called in a loop, and the exception from the SMS leaves the loop. The warehouse still reserves nothing, and the error still reaches the payment. The subject has to protect every call on its own:
public void markPaid(Order order) { for (PaidListener listener : listeners) { try { listener.paid(order); } catch (RuntimeException e) { System.out.println("A subscriber failed: " + e.getMessage()); } }}With the same program:
Payments payments = new Payments();payments.subscribe(email);payments.subscribe(sms);payments.subscribe(warehouse);try { payments.markPaid(new Order(1042, 80));} catch (IllegalStateException e) { System.out.println("Payment failed: " + e.getMessage());}Email: receipt for #1042A subscriber failed: SMS gateway is not respondingWarehouse: reserve #1042The payment went through, the warehouse reserved, and the failure is recorded. In a real shop this line goes to the log, and the SMS is retried later.
Try it
Predict the output
The subscribers are the ones from the card "The subscribers find out on their own". What does the program print?
Payments payments = new Payments();payments.subscribe(email);payments.subscribe(warehouse);payments.subscribe(email);payments.markPaid(new Order(7, 10));
payments.unsubscribe(warehouse);payments.markPaid(new Order(8, 10));Try it
Find the bug
class WelcomeCoupon implements PaidListener { private final Payments payments;
public WelcomeCoupon(Payments payments) { this.payments = payments; }
@Override public void paid(Order order) { System.out.println("Welcome coupon: #" + order.id()); payments.unsubscribe(this); }}Payments payments = new Payments();payments.subscribe(new WelcomeCoupon(payments));payments.subscribe(email);payments.subscribe(warehouse);payments.markPaid(new Order(1042, 80));payments.markPaid(new Order(1043, 25));Welcome coupon: #1042Exception in thread "main" java.util.ConcurrentModificationExceptionThe first order got the coupon, and then the program stopped. Which line in Payments has the bug?
Pick the line with the bug.
ArrayList notices that the list changed during the walk and throws ConcurrentModificationException. A subscriber that unsubscribes as soon as it is notified is normal, so the subject has to handle it: it walks a copy, for (PaidListener listener : List.copyOf(listeners)). Then the coupon is removed from the real list, and the walk goes on over the copy. Email and the warehouse hear about both orders, and the coupon only about the first.More precisely, if you are curious
In C# and JavaScript this bug doesn't happen if you use the built-in tools. The delegate of a C# event doesn't change: -= makes a new list, and the current notification goes on over the old one. emit in EventEmitter copies the list before calling the listeners. A list of your own you have to protect by hand.
The idea
When you don't need it
Observer has a price. The code doesn't say who will react to the payment: to find out, you search for every place that subscribes. A subscriber nobody unsubscribes lives in memory as long as the subject lives. It's not worth it when:
- there is one reaction and it is always the same. One call is clearer than a list with one subscriber;
- the step is part of the action itself. If the payment is invalid without an invoice, the invoice is not a subscriber: it is called directly, and its failure stops the payment;
- the order matters and the steps depend on each other (first the warehouse, then the payment, then the invoice). That is a sequence, not an event. How to put it in one place is in the lesson "Adapter and Facade".
It's worth it when the reactions are many, they grow, and the subject must not depend on them: notifications, points, statistics, logs.
Exercise
The invoice as a subscriber
Solve the task in your editor.
Invoice. Make the invoice a subscriber: a lambda invoice of type PaidListener that prints the amount with two digits after the point. Subscribe email, the warehouse and the invoice, and pay order #1042 for €80. The payments are not touched.
Email: receipt for #1042Warehouse: reserve #1042Invoice: €80.00 for #1042More tasks
- A gift over €100. A subscriber that prints "Gift: free delivery for #…" only for orders over €100. Pay one for €80 and one for €120.
- The coupon that unsubscribes itself. Write the coupon subscriber from "Find the bug" and payments that handle it. Walk a copy of the list.
- Two events. Add refunds too. A second list of subscribers and a
markRefundedmethod. Email listens to both, the warehouse only to the payment.
Test
Check yourself
Related lessons
Section titled "Related lessons"- Builds on: Lambdas · record, switch and patterns · Design patterns · Strategy
- Continues in: The shop: which pattern where · Events and queues · Transactional outbox
- Tasks on this topic: Design patterns