---
title: "SP6 - Kho Dùng Chung (Flyweight / Object Pool) - Học Design Pattern Từ Những Thứ Đơn Giản"
description: "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."
pubDate: "2023-05-19"
lang: "vi"
slug: "sp6-object-pool-learn-design-pattern-from-simple-things"
url: "https://hoangyell.com/vi/sp6-object-pool-learn-design-pattern-from-simple-things/"
author: "HoangYell"
translation_en: "https://hoangyell.com/sp6-object-pool-learn-design-pattern-from-simple-things/"
categories: ["Software Craft"]
tags: ["design-patterns", "structural-patterns"]
heroImage: "https://raw.githubusercontent.com/HoangGeek/store/main/webp/photo-1628354219577-1059383b3929.webp"
---

_Flyweight (gọi thân thiện là "Object Pool" trong bài này) là một mẫu thiết kế nhóm **Structural**:_
🖤🖤🖤🤍🤍 *(Độ hữu dụng trong Python: 3/5)*

> **Lưu ý thuật ngữ:** Trong GoF, **Flyweight** chia sẻ đồng thời các object bất biến dùng chung để tiết kiệm RAM (chính là thứ bài này minh họa), còn **Object Pool** đúng nghĩa thường dùng cho tài nguyên mutable/độc quyền (như DB connection pool) với cơ chế mượn và trả (`acquire()`/`release()`).

## Flyweight (Object Pool) là gì?

Thay vì cấp phát hàng nghìn object trùng lặp dữ liệu nặng giống hệt nhau, bạn lưu **mỗi loại đúng một instance dùng chung** trong cache (`plane_pool`) và truyền phần dữ liệu khác biệt vào dưới dạng tham số khi gọi hàm:
- **Intrinsic state (trạng thái nội tại)** (`model`): dữ liệu dùng chung không đổi, lưu bên trong object cached.
- **Extrinsic state (trạng thái bên ngoài)** (`color`): dữ liệu riêng theo từng ngữ cảnh, truyền từ ngoài vào lúc gọi method.

![Image](https://raw.githubusercontent.com/HoangGeek/store/main/webp/60cd130c-af72-43b1-af79-59340337b1ed.webp)

```markdy
scene duration=18 layout=LR width=1280 height=720
theme: light=doodle dark=nebula

user Caller "Xin Boeing 747 hai lần"
gateway Factory "PlaneFactory.get_plane(model)" icon=python
storage Pool "plane_pool cache (intrinsic: model)"
service Shared "1 instance Plane('Boeing 747') duy nhất"

beat cache "1. Gọi lặp lại vẫn trả đúng 1 object":
  show $nodes stagger=50ms
  Caller -> Factory "get_plane('Boeing 747')"
  Factory -> Pool "Tạo 1 lần rồi dùng lại"
  Pool -> Shared "white_plane is another_white_plane == True"
  glow Pool color=#3b82f6

beat extrinsic "2. Truyền màu sắc extrinsic lúc gọi":
  Caller -> Shared "get_color('white') / get_flight_distance(800, 10)"
  Caller <- Shared "white / 8000"
  glow Shared 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 Flyweight?
- **Tiết kiệm RAM** khi hệ thống sinh ra lượng lớn object na ná nhau (hạt hiệu ứng trong game, tile bản đồ, glyph văn bản).
- **Đánh đổi**: Tăng thêm một tầng indirection và bắt buộc object dùng chung phải giữ bất biến (nếu một chỗ sửa `Plane.model` thì mọi chỗ khác bị vạ lây).

**Hỏi:** _Tôi ghét pattern này, Python có cách nào gọn hơn không?_

**Đáp:** _Nếu chỉ muốn object nhẹ RAM hơn, hãy thử `__slots__` trước. Nếu chỉ muốn cache kết quả khởi tạo hoặc hàm lặp lại, Python có sẵn `@functools.lru_cache` và `sys.intern()`._

![Image](https://sayingimages.com/wp-content/uploads/the-laughing-airplane-meme.jpg.webp)

## Khi nào dùng Flyweight?

**Hỏi:** _Khi nào thì nên dùng?_

**Đáp:** _Khi profiling cho thấy hàng nghìn object đang nhân bản cùng một đống dữ liệu bất biến giống nhau, và bạn tách được phần cố định (`model`) ra khỏi phần biến thiên theo ngữ cảnh (`color`)._

### Đầu vào:

Hai class `Plane` và `PlaneFactory`.

```python
class Plane:
    def __init__(self, model, color):
        self.model = model
        self.color = color

    def get_flight_distance(self, speed, time):
        flight_distance = speed * time
        return flight_distance

class PlaneFactory:
    def __init__(self):
        self.color = {"Boeing 747": "white", "Airbus A380": "blue"}

    def get_plane(self, model):
        color = self.color.get(model, "gray")
        plane = Plane(model, color)
        return plane
```

### Kết quả mong muốn:

Tách `model` (intrinsic) khỏi `color` (extrinsic), mỗi dòng máy bay chỉ tạo đúng 1 instance trong `plane_pool` và truyền `color` vào `get_color(color)` khi cần.

```python
# Create planes
# white_plane = factory.get_plane("Boeing 747")
# blue_plane = factory.get_plane("Airbus A380")
# another_white_plane = factory.get_plane("Boeing 747")
# print(white_plane is another_white_plane)
True

# Get the color for each plane
white
blue

# Get the distance for each plane
8000
10800
```

## Triển khai Flyweight:

### Cách viết không dùng Flyweight (tạo object mới mỗi lần gọi):

```python
class Plane:
    def __init__(self, model, color):
        self.model = model
        self.color = color

    def get_flight_distance(self, speed, time):
        flight_distance = speed * time
        return flight_distance

class PlaneFactory:
    def __init__(self):
        self.color = {"Boeing 747": "white", "Airbus A380": "blue"}

    def get_plane(self, model):
        color = self.color.get(model, "gray")
        plane = Plane(model, color)
        return plane

if __name__ == "__main__":
    factory = PlaneFactory()

    white_plane = factory.get_plane("Boeing 747")
    blue_plane = factory.get_plane("Airbus A380")
    another_white_plane = factory.get_plane("Boeing 747")
    print(white_plane is another_white_plane)
    print(white_plane.color)
    print(blue_plane.color)
    print(white_plane.get_flight_distance(800, 10))
    print(blue_plane.get_flight_distance(900, 12))
```

### Cách viết dùng Flyweight (Object Pool):

```python
class Plane:
    def __init__(self, model):
        # Intrinsic state: shared across contexts
        self.model = model

    def get_color(self, color):
        # Extrinsic state: supplied by the caller/context
        return color

    def get_flight_distance(self, speed, time):
        flight_distance = speed * time
        return flight_distance

class PlaneFactory:
    def __init__(self):
        self.plane_pool = {}

    def get_plane(self, model):
        if model not in self.plane_pool:
            self.plane_pool[model] = Plane(model)
        return self.plane_pool[model]

if __name__ == "__main__":
    factory = PlaneFactory()

    white_plane = factory.get_plane("Boeing 747")
    blue_plane = factory.get_plane("Airbus A380")
    another_white_plane = factory.get_plane("Boeing 747")
    print(white_plane is another_white_plane)
    print(white_plane.get_color("white"))
    print(blue_plane.get_color("blue"))
    print(white_plane.get_flight_distance(800, 10))
    print(blue_plane.get_flight_distance(900, 12))
```

`Plane` chỉ giữ `model`, `PlaneFactory.plane_pool` cache mỗi dòng máy bay đúng một instance (`white_plane is another_white_plane` trả về `True`), còn `get_color(color)` nhận màu sắc từ bên ngoài lúc sử dụng mà không làm phình bộ nhớ pool.

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

***

**Điều hướng series:** Trước: [SP5 - Facade](https://hoangyell.com/vi/sp5-facade-learn-design-pattern-from-simple-things/) · Tiếp theo: [SP7 - Proxy](https://hoangyell.com/vi/sp7-proxy-learn-design-pattern-from-simple-things/)
