SP3 - Cây (Composite) - Học Design Pattern Từ Những Thứ Đơn Giản
Cần lưu trữ lá cây theo tầng lớp để thỉnh thoảng đếm hoặc duyệt toàn bộ? Cấu trúc Cây (Composite) giúp bạn thao tác đồng nhất cả cành lẫn lá.

Tree (Composite) là một mẫu thiết kế nhóm Structural: 🖤🖤🖤🖤🖤 (Độ hữu dụng trong Python: 5/5)
Tree (Composite) là gì?
Tree là một cấu trúc chứa các Cành (Branch) và Lá (Leaf). Nhờ chúng có chung một tên hàm (operation), ta có thể đệ quy duyệt cả cái cây để gom kết quả cực gọn.
Tại sao dùng Tree?
Khi dữ liệu có dạng phân cấp (thư mục & file, menu lồng nhau, comment đa cấp), dùng Tree giúp code duyệt đệ quy sạch sẽ nhất, gần như không có lựa chọn nào gọn hơn.
Hỏi: Branch cũng chỉ là vật chứa thôi đúng không? Sao không nhét leaves vào list cho lẹ?
Đáp: Branch đúng là vật chứa, nhưng nó có sẵn method def operation trùng tên với Leaf. Nhờ vậy bên gọi chỉ cần gọi .operation() đồng nhất trên bất kỳ nút nào mà không cần phân biệt đó là cành hay lá.
Khi nào dùng Tree?
Hỏi: Khi nào tôi cần dùng Tree?
Đáp: Khi dữ liệu có cấu trúc phân tầng cha - con và bạn muốn gọi cùng một thao tác lên từng phần tử lẫn cả cụm phần tử.
Đầu vào:
- Có nhiều chiếc lá (
Leaf). - Có cây phân cấp chứa cành và lá.
class Leaf:
def operation(self):
return "🍁"
container_1 = []
container_1.append(Leaf())
container_1.append(Leaf())
container_2 = []
container_2.append(Leaf())
wormy_leaf = Leaf()
containers = []
containers.append(container_1)
containers.append(Leaf())
containers.append(wormy_leaf)
containers.append(container_2)
containers.remove(wormy_leaf)
Kết quả mong muốn:
- Toàn bộ lá được lưu theo cấu trúc cây phân tầng.
- Duyệt qua và in ra kết quả của tất cả các lá.
[['🍁', '🍁'], '🍁', ['🍁']]
Triển khai Tree:
Cách viết không dùng Tree (dùng list lồng nhau):
class Leaf:
def operation(self):
return "🍁"
def collect_leaves(nested_list):
results = []
for item in nested_list:
item_result = collect_leaves(item) if isinstance(item, list) else item.operation()
results.append(item_result)
return results
if __name__ == "__main__":
container_1 = []
container_1.append(Leaf())
container_1.append(Leaf())
container_2 = []
container_2.append(Leaf())
wormy_leaf = Leaf()
containers = []
containers.append(container_1)
containers.append(Leaf())
containers.append(wormy_leaf)
containers.append(container_2)
containers.remove(wormy_leaf)
print(collect_leaves(containers))
Cách viết dùng Tree (Composite):
from abc import ABC, abstractmethod
class Component(ABC):
_parent = None
@property
def parent(self):
return self._parent
@parent.setter
def parent(self, parent):
self._parent = parent
def add(self, component):
pass
def remove(self, component):
pass
@abstractmethod
def operation(self):
pass
class Leaf(Component):
"""
A leaf can't have any children.
Leaf objects do the actual work.
"""
def operation(self):
return "🍁"
class Branch(Component):
"""
A branch can have children(leaves or baby branches) .
Branch objects do nothing but contain children
"""
def __init__(self):
self._children = []
def add(self, component):
component.parent = self
self._children.append(component)
def remove(self, component):
component.parent = None
self._children.remove(component)
def operation(self):
results = []
for child in self._children:
results.append(child.operation())
return results
if __name__ == "__main__":
branch_1 = Branch()
branch_1.add(Leaf())
branch_1.add(Leaf())
branch_2 = Branch()
branch_2.add(Leaf())
wormy_leaf = Leaf()
tree = Branch()
tree.add(branch_1)
tree.add(Leaf())
tree.add(wormy_leaf)
tree.add(branch_2)
tree.remove(wormy_leaf)
print(tree.operation())
Điều hướng series: Trước: SP2 - Decorator & Closure · Tiếp theo: SP4 - Mixer (Bridge)
Bài viết liên quan
- Software Craft
SP7 - Bảo Vệ (Proxy) - Học Design Pattern Từ Những Thứ Đơn Giản
Sếp chặn mạng giờ làm việc để nhân viên tập trung. Đó chính là cách mẫu Proxy hoạt động: đứng giữa kiểm soát truy cập trước khi gọi object thật.
4 phút đọcĐọc tiếp → - Software Craft
SP6 - Kho Dùng Chung (Flyweight / Object Pool) - Học Design Pattern Từ Những Thứ Đơn Giản
Sản xuất máy bay rất tốn kém, nhưng khung máy giống nhau có thể dùng chung từ một kho cache. Hiểu đúng Flyweight vs Object Pool trong Python.
4 phút đọcĐọc tiếp → - Software Craft
SP5 - Mặt Tiền (Facade) - Học Design Pattern Từ Những Thứ Đơn Giản
Nhiều phòng ban nhưng chỉ cần một cửa đón tiếp. Mẫu Facade gom hệ thống rắc rối vào một giao diện gọn gàng trong Python.
4 phút đọcĐọc tiếp → - Software Craft
SP4 - Máy Lai Giống (Bridge) - Học Design Pattern Từ Những Thứ Đơn Giản
Quản lý trang trại chó với đủ giống và kiểu lông mà không muốn đẻ ra hàng chục subclass lai ghép? Học mẫu Bridge (Mixer) bằng Python.
5 phút đọcĐọc tiếp →