Python Memento Pattern (Memento)
The Memento pattern is a behavioral design pattern that allows capturing and saving an object's internal state without breaking encapsulation, so that it can be restored to a previous state when needed.
Imagine you are playing a game that provides a "save" feature. You can save your current progress at any time; if you later fail or want to retry a level, you can load the previous save. The Memento pattern is the programming solution that implements this "save-load" functionality.
Why is the Memento pattern needed?
Application scenarios
- Text Editor: Implement Undo and Redo functionality
- Game Development: Save game progress and state
- Graphics software: Support operation history
- Transaction processing: Roll back to a previous state when an operation fails
Problem Solved
- You need to save object state but do not want to expose internal details
- Provides a state restoration mechanism, supporting an "undo" feature
- Maintains object encapsulation and avoids mixing state-saving logic with business logic
Core components of the Memento pattern
The Memento pattern contains three main roles:
1. Originator
- The object whose state needs to be saved
- Creates a memento to record the current state
- Uses the memento to restore a previous state
2. Memento
- Stores the internal state of the Originator object
- Prevents objects other than the Originator from accessing the memento's contents
3. Caretaker
- Responsible for saving the memento
- Cannot operate on or inspect the memento's contents

Python implementation of the Memento pattern
Let us implement the Memento pattern concretely through a text editor example.
Basic Implementation
Example
class
TextEditorMemento:
"""Memento class - saves the state of the text editor"""
def
init
(
self
,
content
)
:
self
._content
=
content
def
get_content
(
self
)
:
"""Get the saved content"""
return
self
._content
class
TextEditor:
"""Originator class - Text editor"""
def
init
(
self
)
:
self
._content
=
""
def
write
(
self
,
text
)
:
"""Write text"""
self
._content +
=
text
def
get_content
(
self
)
:
"""Get the current content"""
return
self
._content
def
save
(
self
)
:
"""Create a memento - save the current state"""
return
TextEditorMemento
(
self
._content
)
def
restore
(
self
,
memento
)
:
"""Restore state - read from the memento"""
self
._content
=
memento.
get_content
(
)
class
HistoryManager:
"""Caretaker class - history manager"""
def
init
(
self
)
:
self
._mementos
=
[
]
def
push
(
self
,
memento
)
:
"""Save a memento"""
self
._mementos.
append
(
memento
)
def
pop
(
self
)
:
"""Get the latest memento"""
if
self
._mementos:
return
self
._mementos.
pop
(
)
return
None
Complete example code
Example
Complete Memento pattern example
def
memo_pattern_demo
(
)
:
Create the text editor and history manager
editor
=
TextEditor
(
)
history
=
HistoryManager
(
)
(
"=== Text editor Memento pattern demo ===\n"
)
First edit and save
editor.
write
(
"Hello, "
)
history.
push
(
editor.
save
(
)
)
(
f
"Current content: {editor.get_content()}"
)
(
"✅ State saved\n"
)
Second edit and save
editor.
write
(
"World!"
)
history.
push
(
editor.
save
(
)
)
(
f
"Current content: {editor.get_content()}"
)
(
"✅ State saved\n"
)
Third edit without saving
editor.
write
(
" This is new text."
)
(
f
"Current content: {editor.get_content()}"
)
(
"❌ Current edit not saved\n"
)
Undo operation - restore to the last saved state
memento
=
history.
pop
(
)
if
memento:
editor.
restore
(
memento
)
(
f
"Content after undo: {editor.get_content()}"
)
(
"↩️ Undone to the previous save point\n"
)
Undo again
memento
=
history.
pop
(
)
if
memento:
editor.
restore
(
memento
)
(
f
"Content after undoing again: {editor.get_content()}"
)
(
"↩️ Undone to the initial state"
)
Run the demo
if
name
==
"main"
:
memo_pattern_demo
(
)
Running result:

Advanced application: mementos supporting multiple states
In real applications, we may need to save multiple attributes of an object. Here is a more complex example:
Example
import
datetime
import
json
class
GameStateMemento:
"""Game state memento"""
def
init
(
self
,
level
,
score
,
player_health
,
inventory
)
:
self
._state
=
{
'level'
: level
,
'score'
: score
,
'player_health'
: player_health
,
'inventory'
: inventory.
copy
(
)
,
Create a copy to avoid reference issues
'timestamp'
:
datetime
.
datetime
.
now
(
)
.
isoformat
(
)
}
def
get_state
(
self
)
:
"""Get the complete state"""
return
self
._state.
copy
(
)
def
get_timestamp
(
self
)
:
"""Get the save time"""
return
self
._state
[
'timestamp'
]
class
Game:
"""Game class - Originator"""
def
init
(
self
)
:
self
.
level
=
1
self
.
score
=
0
self
.
player_health
=
100
self
.
inventory
=
[
'sword'
,
'potion'
]
def
play
(
self
,
level_increase
=
1
,
score_increase
=
100
,
health_change
=
0
,
new_item
=
None
)
:
"""Simulate game progress"""
self
.
level
=
level_increase
self
.
score
=
score_increase
self
.
player_health
=
health_change
if
new_item
and
new_item
not
in
self
.
inventory
:
self
.
inventory
.
append
(
new_item
)
Health cannot be negative
self
.
player_health
=
max
(
0
,
self
.
player_health
)
def
display_status
(
self
)
:
"""Display the current state"""
status
=
f
"""
🎮 Game state:
Level: {self.level}
Score: {self.score}
Health: {self.player_health}
Inventory: {', '.join(self.inventory)}
"""
(
status
)
def
save_game
(
self
)
:
"""Save the game state"""
return
GameStateMemento
(
self
.
level
,
self
.
score
,
self
.
player_health
,
self
.
inventory
)
def
load_game
(
self
,
memento
)
:
"""Load the game state"""
state
=
memento.
get_state
(
)
self
.
level
=
state
[
'level'
]
self
.
score
=
state
[
'score'
]
self
.
player_health
=
state
[
'player_health'
]
self
.
inventory
=
state
[
'inventory'
]
class
SaveManager:
"""Save manager"""
def
init
(
self
)
:
self
.
saves
=
{
}
def
create_save
(
self
,
save_name
,
memento
)
:
"""Create a save"""
self
.
saves
[
save_name
]
=
memento
(
f
"💾 Save '{save_name}' created successfully!"
)
def
load_save
(
self
,
save_name
)
:
"""Load a save"""
if
save_name
in
self
.
saves
:
(
f
"🔄 Loading save '{save_name}'..."
)
return
self
.
saves
[
save_name
]
else
:
(
f
"❌ Save '{save_name}' does not exist!"
)
return
None
def
list_saves
(
self
)
:
"""List all saves"""
if
not
self
.
saves
:
(
"📁 No saves yet"
)
return
(
"\n📋 Save list:"
)
for
name
,
memento
in
self
.
saves
.
items
(
)
:
timestamp
=
memento.
get_timestamp
(
)
(
f
" - {name} (saved at: {timestamp})"
)
Advanced example demo
def
advanced_memo_demo
(
)
:
(
"=== Game save system demo ===\n"
)
game
=
Game
(
)
save_manager
=
SaveManager
(
)
Initial state
(
"🎯 Start a new game:"
)
game.
display_status
(
)
Game progress
(
"🚀 Playing the game..."
)
game.
play
(
level_increase
=
2
,
score_increase
=
500
,
new_item
=
'shield'
)
game.
display_status
(
)
Save the first save
save_manager.
create_save
(
"Level 1 cleared"
,
game.
save_game
(
)
)
Continue the game
(
"⚔️ Continue the adventure..."
)
game.
play
(
level_increase
=
1
,
score_increase
=
200
,
health_change
=
30
,
new_item
=
'magic_wand'
)
game.
display_status
(
)
Save the second save
save_manager.
create_save
(
"Level 2 begins"
,
game.
save_game
(
)
)
Display the save list
save_manager.
list_saves
(
)
Load the first save
(
"\n⏪ Back to the state after clearing level 1:"
)
first_save
=
save_manager.
load_save
(
"Level 1 cleared"
)
if
first_save:
game.
load_game
(
first_save
)
game.
display_status
(
)
Run the advanced example
if
name
==
"main"
:
advanced_memo_demo
(
)
Advantages and disadvantages of the Memento pattern
Advantages
- Encapsulation protection: Does not expose internal state, maintaining encapsulation
- Simplifies the Originator: Separates state-saving logic from business logic
- Easy to implement restoration: Provides a simple state restoration mechanism
- Supports multiple undos: Can save states at multiple points in time
Disadvantages
- Memory Consumption: If the state is large or saved frequently, it consumes a lot of memory
- Caretaker overhead: Requires an extra class to manage mementos
- Lifecycle management: Requires proper handling of memento creation and destruction
Best practices and notes
1. Memory optimization strategies
Example
Limit the number of saved history records
class
LimitedHistoryManager:
def
init
(
self
,
max_size
=
10
)
:
self
._mementos
=
[
]
self
._max_size
=
max_size
def
push
(
self
,
memento
)
:
if
len
(
self
._mementos
)
=
self
._max_size:
Remove the oldest records
self
._mementos.
pop
(
0
)
self
._mementos.
append
(
memento
)
2. Handling complex object states
For objects containing complex references, ensure the memento creates a deep copy:
Example
import
copy
class
ComplexMemento:
def
init
(
self
,
complex_state
)
:
Use deep copy to avoid reference issues
self
._state
=
copy
.
deepcopy
(
complex_state
)
3. Selective saving
Not all states need to be saved; you can choose to save only important attributes:
Example
def
create_selective_memento
(
self
)
:
"""Selectively save important states"""
important_state
=
{
'essential_data'
:
self
.
essential_data
,
'critical_settings'
:
self
.
critical_settings
Ignore temporary data and caches
}
return
SelectiveMemento
(
important_state
)
Practical Application Scenarios
1. Graphic editor
Example
class
GraphicEditor:
def
save_state
(
self
)
:
return
GraphicMemento
(
self
.
selected_shapes
.
copy
(
)
,
self
.
canvas_state
,
self
.
view_settings
)
2. Configuration manager
Example
class
ConfigManager:
def
backup_config
(
self
)
:
return
ConfigMemento
(
self
.
current_settings
.
copy
(
)
,
self
.
user_preferences
)
3. Transaction operations
Example
class
DatabaseTransaction:
def
create_checkpoint
(
self
)
:
return
TransactionMemento
(
self
.
connection_state
,
self
.
pending_operations
.
copy
(
)
)
Summary
The Memento pattern is a powerful and practical design pattern that provides an elegant state-saving and restoration mechanism. By separating state-saving logic from business logic, it not only keeps the code clean but also enhances system maintainability.
Key points:
- The core of the Memento pattern is the "save-restore" mechanism
- The three core roles each perform their own duties with clear responsibilities
- In actual use, pay attention to memory management and state selection
- Suitable for scenarios requiring undo, redo, or state rollback