CP4 - Prototype - Học Design Pattern Từ Những Thứ Đơn Giản
Con robot gắn bó lâu năm có đầy ký ức mà dây chuyền bình thường không sản xuất được. Tìm hiểu Prototype trong Python và lỗi deepcopy kinh điển.

Prototype là một mẫu thiết kế nhóm Creational: 🖤🤍🤍🤍🤍 (Độ hữu dụng trong Python: 1/5)
Prototype là gì?
Prototype là kỹ thuật giúp nhân bản (clone) một object có sẵn thay vì khởi tạo lại từ đầu.
Tại sao dùng Prototype?
- Để copy nguyên xi một object đang có.
- Thực tế bạn không cần học Prototype kiểu GoF trong Python, vì module
copytích hợp sẵn làm hết việc này rồi.- Mọi object trong Python đều clone được bằng
copy. - Lưu ý: ví dụ ghi đè
def __deepcopy__trên refactoring.guru vừa rườm rà vừa sai logic. Đừng copy theo họ, cứ dùng thẳng modulecopychuẩn của Python.
- Mọi object trong Python đều clone được bằng
Hỏi: Vậy… bài blog này viết ra để làm gì?
Đáp: Để bạn biết là không cần cày Prototype trong Python, đọc xong rồi nhảy qua pattern tiếp theo cho nhanh.
Khi nào dùng Prototype?
Hỏi: Khi nào thì tôi đang dùng Prototype?
Đáp: Mỗi lần bạn gọi copy.copy hoặc copy.deepcopy, chính là bạn đang dùng Prototype rồi.
Đầu vào:
- Có sẵn một object gốc
Robot - Tạo bản sao
copied_robottừorigin_robot:- Dùng (shallow)
copy:copied_robot.mutable↔️ dùng chung tham chiếu vớiorigin_robot.mutable
- Dùng
deepcopy:copied_robot.mutable🛡️ tách độc lập hoàn toàn vớiorigin_robot.mutable
- Dùng (shallow)
Đọc thêm về mutable và immutable trong Python
import copy
class MemoryRobot:
def __init__(self):
self.who_am_i = None
def set_memory(self, who_am_i):
self.who_am_i = who_am_i
class Robot:
def __init__(self, age, body_parts, memory):
self.age = age
self.body_parts = body_parts
self.memory = memory
@property
def id(self):
# https://www.digitalocean.com/community/tutorials/python-id
return str(id(self))[-3:]
if __name__ == "__main__":
def init_robot():
robot_body_parts = [
"head",
{"left hand", "chest", "right hand"},
["left foot", "butt", "right foot"],
]
memory_robot = MemoryRobot()
robot = Robot(18, robot_body_parts, memory_robot)
memory_robot.set_memory(robot)
return robot
def copy_robot(origin_robot, copy_method):
wing = "wing"
tail = "tail"
tab = " "
tab_2 = " " * 2
tab_3 = " " * 3
print(f"\nCopying by {copy_method.__name__}:")
copied_robot = copy_method(origin_robot)
copied_robot.body_parts.append(tail)
is_origin_robot_changed = origin_robot.body_parts[-1] == tail
print(f"{tab}Question: update copied_robot changes origin_robot?")
print(f"{tab_2}Answer: {is_origin_robot_changed}")
origin_robot.body_parts[1].add(wing)
is_copied_robot_changed = wing in copied_robot.body_parts[1]
print(f"{tab}Question: update origin_robot changes copied_robot?")
print(f"{tab_2}Answer: {is_copied_robot_changed}")
print(f"{tab}How about reference?")
print(f"{tab_2}origin_robot reference:")
print(f"{tab_3}{origin_robot.id} is the ID of origin_robot")
print(
f"{tab_3}{origin_robot.memory.who_am_i.id} is the ID of origin_robot.memory.who_am_i"
)
print(f"{tab_2}copied_robot reference:")
print(f"{tab_3}{copied_robot.id} is the ID of copied_robot")
print(
f"{tab_3}{copied_robot.memory.who_am_i.id} is the ID of copied_robot.memory.who_am_i"
)
return copied_robot
origin_robot_1 = init_robot()
shallow_copied_robot = copy_robot(origin_robot_1, copy.copy)
origin_robot_2 = init_robot()
deep_copied_robot = copy_robot(origin_robot_2, copy.deepcopy)
Kết quả mong muốn:
Copying by copy:
Question: update copied_robot changes origin_robot?
Answer: True
Question: update origin_robot changes copied_robot?
Answer: True
How about reference?
origin_robot reference:
100 is the ID of origin_robot
100 is the ID of origin_robot.memory.who_am_i
copied_robot reference:
101 is the ID of copied_robot
100 is the ID of copied_robot.memory.who_am_i
Copying by deepcopy:
Question: update copied_robot changes origin_robot?
Answer: False
Question: update origin_robot changes copied_robot?
Answer: False
How about reference?
origin_robot reference:
200 is the ID of origin_robot
200 is the ID of origin_robot.memory.who_am_i
copied_robot reference:
201 is the ID of copied_robot
201 is the ID of copied_robot.memory.who_am_i
So sánh cách triển khai:
Cách viết sai trên Refactoring.guru:
class Robot:
...
def __copy__(self):
body_parts = copy.copy(self.body_parts)
memory = copy.copy(self.memory)
copied_robot = self.__class__(self.age, body_parts, memory)
copied_robot.__dict__.update(self.__dict__)
return copied_robot
def __deepcopy__(self, _=None):
if _ is None:
_ = {}
body_parts = copy.deepcopy(self.body_parts, _)
memory = copy.deepcopy(self.memory, _)
copied_robot = self.__class__(self.age, body_parts, memory)
copied_robot.__dict__ = copy.deepcopy(self.__dict__, _)
return copied_robot
...
Cách viết này sai ở đoạn deepcopy:
copied_robotID là401nhưngcopied_robot.memory.who_am_ilại có ID402(khác nhau!).- Lý do: Nó tạo
copied_robotmà quên đăng ký_[id(self)] = copied_robotvào memo dict trước khideepcopyself.memory, làm tham chiếu vòng (circular reference) đẻ ra thêm một bảnRobotthừa.
Copying by copy:
Question: update copied_robot changes origin_robot?
Answer: True
Question: update origin_robot changes copied_robot?
Answer: True
How about reference?
origin_robot reference:
300 is the ID of origin_robot
300 is the ID of origin_robot.memory.who_am_i
copied_robot reference:
301 is the ID of copied_robot
300 is the ID of copied_robot.memory.who_am_i
Copying by deepcopy:
Question: update copied_robot changes origin_robot?
Answer: False
Question: update origin_robot changes copied_robot?
Answer: False
How about reference?
origin_robot reference:
400 is the ID of origin_robot
400 is the ID of origin_robot.memory.who_am_i
copied_robot reference:
401 is the ID of copied_robot
402 is the ID of copied_robot.memory.who_am_i
Source Code: Incorrect Implement
Cách triển khai Prototype chuẩn trong Python:
Bạn đang dùng nó ở phần Đầu vào với copy.deepcopy sẵn rồi, không cần viết thêm dòng nào!
# nothing here
Source Code: Correct Implement
Điều hướng series: Trước: CP3 - Builder · Tiếp theo: CP5 - Singleton
Bài viết liên quan
- Software Craft
CP5 - Singleton - Học Design Pattern Từ Những Thứ Đơn Giản
Giữ một đường dây điện thoại nối thông suốt thay vì cứ nhấc lên rồi cúp máy liên tục. Hiểu mẫu Singleton trong Python bằng metaclass và Lock.
4 phút đọcĐọc tiếp → - Software Craft
CP3 - Builder - Học Design Pattern Từ Những Thứ Đơn Giản
Xây một căn nhà cần lắp ghép nhiều phần với yêu cầu riêng biệt. Xem mẫu Builder hoạt động ra sao và vì sao Python thường không cần tới nó.
3 phút đọcĐọc tiếp → - Software Craft
CP2 - So Sánh Các Loại Factory: Simple Factory vs Factory Method vs Abstract Factory
Simple Factory vừa gọn vừa đủ dùng, còn Factory Method và Abstract Factory thì rườm rà khó hiểu? Cùng bóc tách bằng Python từ ví dụ máy bán nước.
6 phút đọcĐọc tiếp → - Software Craft
CP1 - Máy Bán Nước Tự Động (Factory) - Học Design Pattern Từ Những Thứ Đơn Giản
Đồ uống nằm rải rác khắp các tiệm tạp hóa rất mất công đi tìm. Học cách dùng mẫu Factory để gom việc tạo object về một mối gọn gàng trong Python.
4 phút đọcĐọc tiếp →