BP9 - Lịch Sử File (Memento) - Học Design Pattern Từ Những Thứ Đơn Giản
Tính năng Undo nhìn qua tưởng đơn giản, nhưng bên dưới nó lưu và khôi phục trạng thái như thế nào? Tìm hiểu mẫu Memento bằng Python qua Photoshop.

File History (Memento) là một mẫu thiết kế nhóm Behavioral: 🖤🖤🖤🤍🤍 (Độ hữu dụng trong Python: 3/5)
File History (Memento) là gì?
File History (Memento) cho phép một object chụp lại (save) và khôi phục (restore) trạng thái bên trong của nó tại nhiều mốc thời gian mà không làm lộ chi tiết cài đặt ra bên ngoài. Đây chính là cách làm checkpoint, snapshot và tính năng Undo.
Tại sao dùng File History?
- Tách bạch trách nhiệm:
Photoshoplo việc chỉnh sửa ảnh,Filegiữ bản chụp chỉ đọc, cònSSDStoragelo xếp chồng lịch sử mà không cần soi mói ruộtPhotoshop. - Đánh đổi: Nếu mỗi lần sửa lại chụp nguyên cả cục file nặng thì rất tốn RAM/ổ cứng (lúc đó lưu diff/delta hoặc dùng Command Undo sẽ nhẹ hơn).
Hỏi: Tôi ghét File History, có cách nào khác không?
Đáp: Nhét thẳng _undo_stack vào bên trong Photoshop (như cách Không dùng File History bên dưới), hoặc chụp nhanh trạng thái bằng copy.deepcopy / @dataclass(frozen=True) nếu không cần tách riêng kho lưu trữ SSDStorage.
Khi nào dùng File History?
Hỏi: Khi nào tôi nên dùng File History?
Đáp: Khi bạn cần lưu và khôi phục trạng thái của một object qua nhiều bước mà vẫn giữ kín cấu trúc nội bộ của nó.
Đầu vào:
Class Photoshop cho phép sửa nội dung, xuất bản snapshot File và nạp lại snapshot cũ.
class Photoshop:
def __init__(self):
self._content = ""
# Make the content attribute read-only
@property
def content(self):
return self._content
# Edit the image by adding some text
def edit(self, text):
self._content += text
# Save the current state of the image inside a file
def save(self):
return File(self.content)
# Load the previous state of the image from a file
def load(self, file):
if file is not None:
self._content = file.content
# Define how the photoshop object is printed
def __str__(self):
return self.content
Kết quả mong muốn:
Chỉnh sửa qua 3 màu rồi Undo lùi từng bước một:
Current: RedGreenBlue
Undo: RedGreen
Undo: Red
Triển khai File History:
Cách viết không dùng File History (tự giữ _undo_stack trong Photoshop):
class File:
def __init__(self, content):
self._content = content
@property
def content(self):
return self._content
def __str__(self):
return self.content
class Photoshop:
def __init__(self):
self._content = ""
self._undo_stack = [] # keep track of previous contents for undoing
@property
def content(self):
return self._content
def edit(self, text):
self._undo_stack.append(self._content) # push the current content to the undo stack
self._content += text # update the content with the new text
def save(self):
return File(self.content)
def load(self, file):
self._content = file.content
def undo(self): # undo the last edit
if self._undo_stack: # check if there is anything to undo
self._content = self._undo_stack.pop() # pop the last content from the undo stack and set it as the current content
else:
print("Nothing to undo.")
def __str__(self):
return self.content
if __name__ == "__main__":
photoshop = Photoshop()
photoshop.edit("Red")
photoshop.save()
photoshop.edit("Green")
photoshop.save()
photoshop.edit("Blue")
photoshop.save()
print(f"Current: {photoshop}")
photoshop.undo()
print(f"Undo: {photoshop}")
photoshop.undo()
print(f"Undo: {photoshop}")
Cách viết dùng File History (Memento):
Chia thành 3 vai trò rõ ràng: Originator (Photoshop), Memento (File), và Caretaker (SSDStorage).
# File class for saving the file data
class File:
def __init__(self, content):
self._content = content
# Make the content attribute read-only
@property
def content(self):
return self._content
# Define how the file object is printed
def __str__(self):
return self.content
# Photoshop class for editing images
class Photoshop:
def __init__(self):
self._content = ""
# Make the content attribute read-only
@property
def content(self):
return self._content
# Edit the image by adding some text
def edit(self, text):
self._content += text
# Save the current state of the image inside a file
def save(self):
return File(self.content)
# Load the previous state of the image from a file
def load(self, file):
if file is not None:
self._content = file.content
# Define how the photoshop object is printed
def __str__(self):
return self.content
# SSDStorage class for managing files
class SSDStorage:
def __init__(self):
self.file_history = []
# Save a file to the history list
def save(self, file):
self.file_history.append(file)
# Get the last file from the history list and remove it
def pop_previous_file(self):
try:
return self.file_history.pop()
except IndexError:
print("No more files to pop.")
return None
if __name__ == "__main__":
ssd_storage = SSDStorage()
photoshop = Photoshop()
ssd_storage.save(photoshop.save())
photoshop.edit("Red")
ssd_storage.save(photoshop.save())
photoshop.edit("Green")
ssd_storage.save(photoshop.save())
photoshop.edit("Blue")
print(f"Current: {photoshop}") # Current: RedGreenBlue
_file = ssd_storage.pop_previous_file()
photoshop.load(_file)
print(f"Undo: {photoshop}") # Undo: RedGreen
_file = ssd_storage.pop_previous_file()
photoshop.load(_file)
print(f"Undo: {photoshop}") # Undo: Red
Nhờ tách SSDStorage ra ngoài, người dùng có thể Undo nhiều bước mà không cần Photoshop tự ôm thêm trách nhiệm quản lý lịch sử.
Điều hướng series: Trước: BP8 - Visitor · Tiếp theo: BP10 - Mediator
Bài viết liên quan
- Software Craft
BP11 - Máy Tính Mini (Interpreter) - Học Design Pattern Từ Những Thứ Đơn Giản
Biến biểu thức lồng nhau như (x + 10) - (y + 2) thành cây cú pháp tự tính toán kết quả theo từng ngữ cảnh. Học mẫu Interpreter trong Python.
5 phút đọcĐọc tiếp → - Software Craft
BP10 - Loa Phóng Thanh (Mediator) - Học Design Pattern Từ Những Thứ Đơn Giản
Sinh viên trong lớp không cần nhắn tin tay cho từng người một mà nói qua chiếc loa trung tâm. Học mẫu Mediator trong Python.
4 phút đọcĐọc tiếp → - Software Craft
BP8 - Điệp Viên Thăm Dò (Visitor) - Học Design Pattern Từ Những Thứ Đơn Giản
Một điệp viên ghé thăm các cơ sở tuyệt mật để thu thập thông tin mà không cần đụng sửa class gốc. Học mẫu Visitor và double dispatch trong Python.
5 phút đọcĐọc tiếp → - Software Craft
BP7 - Khung Mẫu (Template Method) - Học Design Pattern Từ Những Thứ Đơn Giản
Volkswagen giữ chung dây chuyền lắp ráp cho Lamborghini và Porsche nhưng cho tùy biến động cơ và khung gầm. Học Template Method bằng Python.
5 phút đọcĐọc tiếp →