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.

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
PhoneLinemấ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ộtid(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
- Software Craft
CP4 - Prototype - Học Design Pattern Từ Những Thứ Đơn Giản
Con robot gắn bó lâu năm có đầy ký ức mà dây chuyền bình thường không sản xuất được. Tìm hiểu Prototype trong Python và lỗi deepcopy kinh điển.
5 phút đọcĐọc tiếp → - Software Craft
CP3 - Builder - Học Design Pattern Từ Những Thứ Đơn Giản
Xây một căn nhà cần lắp ghép nhiều phần với yêu cầu riêng biệt. Xem mẫu Builder hoạt động ra sao và vì sao Python thường không cần tới nó.
3 phút đọcĐọc tiếp → - Software Craft
CP2 - So Sánh Các Loại Factory: Simple Factory vs Factory Method vs Abstract Factory
Simple Factory vừa gọn vừa đủ dùng, còn Factory Method và Abstract Factory thì rườm rà khó hiểu? Cùng bóc tách bằng Python từ ví dụ máy bán nước.
6 phút đọcĐọc tiếp → - Software Craft
CP1 - Máy Bán Nước Tự Động (Factory) - Học Design Pattern Từ Những Thứ Đơn Giản
Đồ uống nằm rải rác khắp các tiệm tạp hóa rất mất công đi tìm. Học cách dùng mẫu Factory để gom việc tạo object về một mối gọn gàng trong Python.
4 phút đọcĐọc tiếp →