Last modified: 2026-03-03 18:58:29 +0900
View History
Overview
Also known as
Publish/Subscribe model
Purpose
Lets one or more objects be notified of state changes in other objects within the system.
Use When
Loose coupling is needed for communications.
State changes in one or more objects should trigger behavior in other objects.
Broadcasting capabilities are required.
An understanding exists that objects will be blind to the expense of notification.
Example
Application Overview
Create an application using the WeatherData object to update three displays
The WeatherData class
Methods getTemperature(), getHumidity(), getPressure() return the most recent weather measurements for temperature, humidity and pressure respectively.
We don’t care how these variables are set.
The WeatherData object knows how to get updated information from the Weather Station.
Method measurementChanged() gets called whenever the measurements have been updated.
What do we know?
Display elements that use the weather data:
Current conditions display
Statistics display
Forecast display
They must be updated each time WeatherData has new measurements.
System must be expandable
other developers can create new custom display elements and users can add or remove as many display elements as they want to the application.
Currently, we know about only the initial three display types: current conditions, statistics, and forecast.
By coding to concrete implementations we have no way to add or remove other display elements without making changes to the program.
Meet the Obeserver Pattern
A news paper publisher goes into business and begins publishing newspapers.
You subscribe to a particular publisher.
Every time there’s new edition it gets delivered to you.
*As long as you remain a subscriber, you get new newspapers.
You unsubscribe when you don’t want papers anymore.
They stop delivery.
While the publisher remains in business, people, hotels, airlines and other business constantly subscribe and unsubscribe to the newspaper.
Observer Pattern
Publisher & Subscriber Model
Publisher : Subscriber = Subject : Observer
Model OverviewDuck wants to subscribeDuck is now an observer, tooNotifying the observersMouse wants to unsubscribeNotifying the observers
The Observer Pattern Defined
The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically.
Class Diagram for Observer Pattern
The Power of Loose Coupling
Principle of loose coupling
Strive for loosely coupled designs between object that interact.
When two objects are loosely coupled, they can interact, but have very little knowledge of each other.
Observer Pattern provides an object design where subjects and observers are loosely coupled.