Bỏ qua đến nội dung

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.

Hoang Yell
Hoang Yell
4 phút đọc
English
SP6 - Kho Dùng Chung (Flyweight / Object Pool) - Học Design Pattern Từ Những Thứ Đơn Giản

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.

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().

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.

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.

# 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):

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):

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


Điều hướng series: Trước: SP5 - Facade · Tiếp theo: SP7 - Proxy

Bài viết liên quan

yell@hoangyell:~ %

>hoangyell --status

Đang bận chở vợ con đi cafe & chơi với AI ☕🤖

Ủa ai réo Yell đấy? Cần tâm sự chuyện code hay collab thì ghé Instagram tui nè:

Ghé Instagram esc to close