---
title: "SP3 - Cây (Composite) - Học Design Pattern Từ Những Thứ Đơn Giản"
description: "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á."
pubDate: "2023-01-01"
lang: "vi"
slug: "sp3-tree-learn-design-pattern-from-simple-things"
url: "https://hoangyell.com/vi/sp3-tree-learn-design-pattern-from-simple-things/"
author: "HoangYell"
translation_en: "https://hoangyell.com/sp3-tree-learn-design-pattern-from-simple-things/"
categories: ["Software Craft"]
tags: ["design-patterns", "structural-patterns"]
heroImage: "https://raw.githubusercontent.com/HoangGeek/store/main/webp/72PIGmm.webp"
---

_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.

![Image](https://raw.githubusercontent.com/HoangGeek/store/main/webp/210161906-3c5d8744-8b5f-4f96-bc24-21f043fce85b.webp)

```markdy
scene duration=18 layout=TB width=760 height=960
theme: light=doodle dark=nebula

user Caller "Gọi tree.operation()"
service Root "Branch: tree" icon=python
service B1 "Branch: branch_1"
service LMid "Leaf (🍁)"
service B2 "Branch: branch_2"
service L1 "Leaf 1 & Leaf 2 (🍁, 🍁)"
service L2 "Leaf 3 (🍁)"

beat walk "1. Gọi đồng nhất .operation() xuống cây":
  show $nodes stagger=50ms
  Caller -> Root "operation()"
  Root -> B1 "child.operation()"
  Root -> LMid "child.operation()"
  Root -> B2 "child.operation()"
  B1 -> L1 "🍁, 🍁"
  B2 -> L2 "🍁"
  glow Root color=#3b82f6

beat collect "2. Gom kết quả ngược lên gốc":
  Caller <- Root "[['🍁', '🍁'], '🍁', ['🍁']]"
  glow Caller color=#22c55e

player:
  playback:
    loop true
  controls:
    speed true
    speeds "0.25"
    interact true
    fullscreen true
    gif true
    theme true
  interaction:
    zoom true
    pan true
    click_to_play true
    double_click_to_reset true
    keyboard false
  chrome:
    badge true
    progress none
```

## 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.

![Image](https://raw.githubusercontent.com/HoangGeek/store/main/webp/5f9c9f48740569d1a4ca41c4.webp)

**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á.

``` python
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á.
``` shell
[['🍁', '🍁'], '🍁', ['🍁']]
```

## Triển khai Tree:

### Cách viết không dùng Tree (dùng `list` lồng nhau):
``` python
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):
``` python
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())
```

[Source Code](https://github.com/HoangYell/Design-Pattern-From-Simple-Things/blob/main/sp3_tree.py)

***

**Điều hướng series:** Trước: [SP2 - Decorator & Closure](https://hoangyell.com/vi/sp2-decorator-function-decorator-closure-learn-design-pattern-from-simple-things/) · Tiếp theo: [SP4 - Mixer (Bridge)](https://hoangyell.com/vi/sp4-mixer-learn-design-pattern-from-simple-things/)
