Python Observer Pattern
The Observer pattern is a behavioral design pattern that defines a one-to-many dependency relationship, allowing multiple observer objects to listen to a subject object simultaneously. When the subject's state changes, all its observers are notified and update automatically.
The Observer pattern in daily life
Imagine the scenario of newspaper subscription:
- Newspaper publisher(Subject) publishes news
- Subscriber(Observer) subscribes to the newspaper
- When a new newspaper is published, all subscribers automatically receive it
- Subscribers can unsubscribe at any time
This "publish-subscribe" mechanism is a typical application of the Observer pattern.
Core components of the Observer pattern
The Observer pattern contains four key roles:
1. Subject
- Maintains a list of observers
- Provides methods to register and unregister observers
- Notifies all observers of state changes
2. Concrete Subject
- Stores specific state information
- Notifies observers when the state changes
3. Observer
- Defines the update interface for receiving subject notifications
4. Concrete Observer
- Implements the update interface to stay consistent with the subject's state
Implementation of the Observer pattern
Let us understand the implementation of the Observer pattern through a complete example.
Basic Implementation
Example
from
abc
import
ABC
,
abstractmethod
from
typing
import
List
Observer interface
class
Observer
(
ABC
)
:
@
abstractmethod
def
update
(
self
,
message:
str
)
:
"""Observer update method"""
pass
Subject interface
class
Subject
(
ABC
)
:
@
abstractmethod
def
register_observer
(
self
,
observer: Observer
)
:
"""Register an observer"""
pass
@
abstractmethod
def
remove_observer
(
self
,
observer: Observer
)
:
"""Remove an observer"""
pass
@
abstractmethod
def
notify_observers
(
self
)
:
"""Notify all observers"""
pass
Concrete subject - News publisher
class
NewsPublisher
(
Subject
)
:
def
init
(
self
)
:
self
._observers: List
[
Observer
]
=
[
]
self
._latest_news
=
""
def
register_observer
(
self
,
observer: Observer
)
:
"""Register an observer"""
if
observer
not
in
self
._observers:
self
._observers.
append
(
observer
)
(
f
"Observer {observer.class.name} registered successfully"
)
def
remove_observer
(
self
,
observer: Observer
)
:
"""Remove an observer"""
if
observer
in
self
._observers:
self
._observers.
remove
(
observer
)
(
f
"Observer {observer.class.name} removed successfully"
)
def
notify_observers
(
self
)
:
"""Notify all observers"""
(
f
"\nPublishing new message: {self._latest_news}"
)
for
observer
in
self
._observers:
observer.
update
(
self
._latest_news
)
def
publish_news
(
self
,
news:
str
)
:
"""Publish news"""
self
._latest_news
=
news
self
.
notify_observers
(
)
def
get_observer_count
(
self
)
int
:
"""Get the number of observers"""
return
len
(
self
._observers
)
Concrete observer - Email subscriber
class
EmailSubscriber
(
Observer
)
:
def
init
(
self
,
name:
str
)
:
self
.
name
=
name
def
update
(
self
,
message:
str
)
:
"""Receive updates and send email"""
(
f
"[Email] {self.name} received message: {message}"
)
Concrete observer - SMS subscriber
class
SMSSubscriber
(
Observer
)
:
def
init
(
self
,
name:
str
,
phone:
str
)
:
self
.
name
=
name
self
.
phone
=
phone
def
update
(
self
,
message:
str
)
:
"""Receive updates and send SMS"""
(
f
"[SMS] {self.phone} - {self.name} received message: {message}"
)
Concrete observer - App push subscriber
class
AppPushSubscriber
(
Observer
)
:
def
init
(
self
,
username:
str
)
:
self
.
username
=
username
def
update
(
self
,
message:
str
)
:
"""Receive updates and send app push"""
(
f
"[App push] User {self.username} received push: {message}"
)
Usage examples
Example
def
demo_basic_observer
(
)
:
"""Basic Observer pattern demo"""
(
"=== Basic Observer pattern demo ===\n"
)
Create the news publisher
publisher
=
NewsPublisher
(
)
Create different types of subscribers
email_user
=
EmailSubscriber
(
"Zhang San"
)
sms_user
=
SMSSubscriber
(
"Li Si"
,
"13800138000"
)
app_user
=
AppPushSubscriber
(
"Wang Wu"
)
Register subscribers
publisher.
register_observer
(
email_user
)
publisher.
register_observer
(
sms_user
)
publisher.
register_observer
(
app_user
)
(
f
"\nCurrent number of subscribers: {publisher.get_observer_count()}"
)
Publish news
publisher.
publish_news
(
"Python 3.12 officially released!"
)
Remove a subscriber
publisher.
remove_observer
(
sms_user
)
(
f
"\nNumber of subscribers after removal: {publisher.get_observer_count()}"
)
Publish news again
publisher.
publish_news
(
"Observer pattern learning guide is online!"
)
Run the demo
if
name
==
"main"
:
demo_basic_observer
(
)
Running result:
=== 观察者模式基础演示 ===
观察者 EmailSubscriber 注册成功
观察者 SMSSubscriber 注册成功
观察者 AppPushSubscriber 注册成功
当前订阅者数量: 3
发布新消息: Python 3.12 正式发布!
[邮件] 张三 收到消息: Python 3.12 正式发布!
[短信] 13800138000 - 李四 收到消息: Python 3.12 正式发布!
[应用推送] 用户 王五 收到推送: Python 3.12 正式发布!
观察者 SMSSubscriber 移除成功
移除后订阅者数量: 2
发布新消息: 观察者模式学习指南上线!
[邮件] 张三 收到消息: 观察者模式学习指南上线!
[应用推送] 用户 王五 收到推送: 观察者模式学习指南上线!
Advanced application: stock price monitoring system
Let us deepen our understanding through a more practical example.
Example
Stock monitoring system example
class
Stock:
"""Stock class"""
def
init
(
self
,
symbol
:
str
,
price:
float
)
:
self
.
symbol
=
symbol
Stock code
self
._price
=
price
Current price
self
._history
=
[
price
]
Price history
@
property
def
price
(
self
)
float
:
return
self
._price
@
price.
setter
def
price
(
self
,
value:
float
)
:
"""Set the price and record history"""
old_price
=
self
._price
self
._price
=
value
self
._history.
append
(
value
)
return
old_price
,
value
def
get_price_change
(
self
)
float
:
"""Get the percentage price change"""
if
len
(
self
._history
)
<
2
:
return
0.0
return
(
(
self
._history
[
1
]
self
._history
[
2
]
)
/
self
._history
[
2
]
)
100
class
StockMarket
(
Subject
)
:
"""Stock market - Concrete subject"""
def
init
(
self
)
:
self
._observers: List
[
Observer
]
=
[
]
self
._stocks
=
{
}
Stock dictionary: {code: Stock object}
def
register_observer
(
self
,
observer: Observer
)
:
if
observer
not
in
self
._observers:
self
._observers.
append
(
observer
)
def
remove_observer
(
self
,
observer: Observer
)
:
if
observer
in
self
._observers:
self
._observers.
remove
(
observer
)
def
notify_observers
(
self
,
stock: Stock
)
:
"""Notify observers of changes to a specific stock"""
change
=
stock.
get_price_change
(
)
message
=
f
"{stock.symbol}: ${stock.price:.2f} ({change:+.2f}%)"
for
observer
in
self
._observers:
observer.
update
(
message
)
def
add_stock
(
self
,
symbol
:
str
,
initial_price:
float
)
:
"""Add a stock to the market"""
self
._stocks
[
symbol
]
=
Stock
(
symbol
,
initial_price
)
def
update_stock_price
(
self
,
symbol
:
str
,
new_price:
float
)
:
"""Update a stock price and notify observers"""
if
symbol
in
self
._stocks:
stock
=
self
._stocks
[
symbol
]
old_price
,
current_price
=
stock.
price
,
new_price
stock.
price
=
new_price
Only notify when the price actually changes
if
old_price
!=
current_price:
self
.
notify_observers
(
stock
)
class
Investor
(
Observer
)
:
"""Investor - Concrete observer"""
def
init
(
self
,
name:
str
,
interest_stocks: List
[
str
]
=
None
)
:
self
.
name
=
name
self
.
interest_stocks
=
interest_stocks
or
[
]
self
.
notifications
=
[
]
def
update
(
self
,
message:
str
)
:
"""Receive stock updates"""
stock_symbol
=
message.
split
(
":"
)
[
0
]
Only follow stocks of interest
if
not
self
.
interest_stocks
or
stock_symbol
in
self
.
interest_stocks
:
self
.
notifications
.
append
(
message
)
(
f
"Investor {self.name} received: {message}"
)
def
show_notifications
(
self
)
:
"""Display all notifications"""
(
f
"\n=== {self.name}'s notification record ==="
)
for
notification
in
self
.
notifications
:
(
f
" - {notification}"
)
def
demo_stock_market
(
)
:
"""Stock market demo"""
(
"\n=== Stock market monitoring system demo ===\n"
)
Create the stock market
market
=
StockMarket
(
)
Add stocks
market.
add_stock
(
"AAPL"
,
150.0
)
market.
add_stock
(
"GOOGL"
,
2800.0
)
market.
add_stock
(
"TSLA"
,
250.0
)
Create investors
investor1
=
Investor
(
"Technical investor"
,
[
"AAPL"
,
"GOOGL"
]
)
investor2
=
Investor
(
"New energy investor"
,
[
"TSLA"
]
)
investor3
=
Investor
(
"Whole-market investor"
)
Register investors
market.
register_observer
(
investor1
)
market.
register_observer
(
investor2
)
market.
register_observer
(
investor3
)
Simulate stock price changes
(
"Start simulating stock trading..."
)
market.
update_stock_price
(
"AAPL"
,
152.5
)
AAPL rises
market.
update_stock_price
(
"TSLA"
,
245.0
)
TSLA falls
market.
update_stock_price
(
"GOOGL"
,
2820.0
)
GOOGL rises
market.
update_stock_price
(
"AAPL"
,
151.0
)
AAPL drops slightly
Display investor notification records
investor1.
show_notifications
(
)
investor2.
show_notifications
(
)
investor3.
show_notifications
(
)
Run the stock market demo
demo_stock_market
(
)
Advantages and disadvantages of the Observer pattern
Advantages
| Advantages | Description |
|---|---|
| Loose coupling | Loose dependency between subject and observers, allowing independent changes |
| Extensibility | New observers can be added easily without modifying the subject code |
| Broadcast communication | Supports one-to-many communication; messages can be broadcast to multiple objects |
| Open-closed principle | Open for extension, closed for modification |
Disadvantages
| Disadvantages | Description | Solution |
|---|---|---|
| Memory Leaks | Observers forgetting to unregister may cause memory leaks | Use weak references or ensure timely unregistration |
| Update order | Observer update order is uncertain | If order is needed, a priority mechanism can be added |
| Performance Issues | When there are many observers, notifications may affect performance | Use asynchronous notifications or batch updates |
Practical Application Scenarios
1. GUI event handling
Example
Pseudocode example
button.
on_click
(
handler1
)
Register a click event observer
button.
on_click
(
handler2
)
Register another observer
When the button is clicked, all registered handlers are called
2. Message queue system
- Producers publish messages
- Multiple consumers subscribe to and process messages
3. Data monitoring system
- Data source state changes
- Multiple monitoring services receive notifications and take action
4. Game development
- Game event system
- UI elements respond to game state changes
Best practices and notes
1. Use weak references to avoid memory leaks
Example
import
weakref
class
SafeSubject
(
Subject
)
:
def
init
(
self
)
:
self
._observers
=
weakref
.
WeakSet
(
)
Use a collection of weak references
def
register_observer
(
self
,
observer: Observer
)
:
self
._observers.
add
(
observer
)
2. Asynchronous notifications improve performance
Example
import
asyncio
class
AsyncObserver
(
ABC
)
:
@
abstractmethod
async
def
update_async
(
self
,
message:
str
)
:
pass
class
AsyncSubject:
async
def
notify_observers_async
(
self
)
:
tasks
=
[
observer.
update_async
(
self
._message
)
for
observer
in
self
._observers
]
await asyncio.
gather
(
*tasks
)
3. Add error handling
Example
def
safe_notify
(
self
)
:
for
observer
in
self
._observers.
copy
(
)
:
Use a copy to avoid modification issues
try
:
observer.
update
(
self
._message
)
except
Exception
as
e:
(
f
"Observer {observer} update failed: {e}"
)
Summary
The Observer pattern is a very important design pattern in Python; it provides an elegant way to achieve loosely coupled communication between objects. Through this article, you should be able to:
- Understand the core concepts and applicable scenarios of the Observer pattern
- Master the basic implementation methods of the Observer pattern
- Apply the Observer pattern to solve problems in real projects
- Avoid common pitfalls of the Observer pattern