Bỏ qua đến nội dung

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.

Hoang Yell
Hoang Yell
4 phút đọc
English
CP5 - Singleton - Học Design Pattern Từ Những Thứ Đơn Giản

Singleton là một mẫu thiết kế nhóm Creational: 🖤🖤🖤🖤🤍 (Độ hữu dụng trong Python: 4/5)

Singleton là gì?

Singleton đảm bảo cả hệ thống chỉ tạo ra đúng 1 instance duy nhất của một class và dùng chung ở mọi nơi. Nó hay được dùng để quản lý kết nối database, config, hoặc tài nguyên khởi tạo tốn kém.

Tại sao dùng Singleton?

  • Chắc chắn chỉ tồn tại duy nhất một instance trong suốt vòng đời chương trình.
  • Truy cập dùng chung toàn cục dễ dàng.
  • Tránh lãng phí thời gian/bộ nhớ khi khởi tạo lặp đi lặp lại tài nguyên nặng.

Hỏi: Tại sao nhiều người lại coi Singleton là anti-pattern?

Đáp: Vì nó tạo trạng thái toàn cục (global state) làm code bị phụ thuộc ngầm (hidden dependencies), khó viết unit test độc lập và dễ dính coupling chặt chẽ. Nếu truyền thẳng object qua Dependency Injection được thì vẫn sạch hơn.

Khi nào dùng Singleton?

Hỏi: Khi nào tôi nên dùng Singleton?

Đáp: Khi bạn muốn chắc chắn một class chỉ khởi tạo đúng 1 lần để tránh chi phí tạo/hủy lặp lại. (Trong Python, một module thông thường được cache trong sys.modules hoặc @functools.lru_cache(maxsize=1) thường là cách làm Singleton tự nhiên hơn viết metaclass.)

Đầu vào:

  • Một class PhoneLine mất tới 10 giây để kết nối, cần giới hạn chỉ tồn tại 1 instance.
class PhoneLine(metaclass=PhoneLineSingleton):
    def __init__(self):
        sleep(10)

    def talk(self):
        print(f"talking on the {id(self)} line")

Kết quả mong muốn:

  • Mọi nhân viên (employee) đều nói chuyện qua chung một id(self) duy nhất.
talking on the 69 line
talking on the 69 line

Triển khai Singleton:

Cách viết không dùng Singleton:

from time import sleep


class PhoneLine:
    def __init__(self):
        sleep(10)

    def talk(self):
        print(f"talking on the {id(self)} line")


class Employee:
    def __init__(self, phone_line):
        self.phone_line = phone_line

    def call_data_center(self):
        self.phone_line.talk()


# Example usage: each employee creates their own PhoneLine (slow & separate instances)
# (Note: passing one shared PhoneLine via Dependency Injection is also a cleaner alternative to Singleton)
employee1 = Employee(PhoneLine())
employee2 = Employee(PhoneLine())

# Both employees end up with two different PhoneLine instances
employee1.call_data_center()
employee2.call_data_center()

Cách viết dùng Singleton (Metaclass + Thread Lock):

from threading import Lock
from time import sleep


class PhoneLineSingleton(type):
    _instances = {}
    _lock = Lock()

    def __call__(cls, *args, **kwargs):
        """
        __call__ is defined in this metaclass(SingletonMeta), not in the normal_class(Singleton) itself.
        When you create an instance of the Singleton class using Singleton(), Python internally calls the __call__ method of the SingletonMeta metaclass, not the __call__ method of the Singleton class.
        In this way, the __call__ method in the metaclass is used to control the creation of instances of the Singleton class, while the __call__ method in the Singleton class can be used for other purposes, if needed.
        This separation of concerns between the metaclass and the class itself is a key feature of the singleton pattern implementation in the given code. It allows us to enforce the singleton pattern without modifying the interface or behavior of the Singleton class itself.
        """
        with cls._lock:
            if cls not in cls._instances:
                instance = super().__call__(*args, **kwargs)
                cls._instances[cls] = instance
        return cls._instances[cls]


class PhoneLine(metaclass=PhoneLineSingleton):
    def __init__(self):
        sleep(10)

    def talk(self):
        print(f"talking on the {id(self)} line")


# Example usage:
phone_line_1 = PhoneLine()
phone_line_2 = PhoneLine()

# Both objects refer to the same instance
phone_line_1.talk()
phone_line_2.talk()

Source Code: Singleton Implement


Điều hướng series: Trước: CP4 - Prototype · Tiếp theo: SP1 - Adapter

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