---
title: "CP5 - Singleton - Học Design Pattern Từ Những Thứ Đơn Giản"
description: "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."
pubDate: "2022-12-25"
lang: "vi"
slug: "cp5-singleton-learn-design-pattern-from-simple-things"
url: "https://hoangyell.com/vi/cp5-singleton-learn-design-pattern-from-simple-things/"
author: "HoangYell"
translation_en: "https://hoangyell.com/cp5-singleton-learn-design-pattern-from-simple-things/"
categories: ["Software Craft"]
tags: ["design-patterns", "creational-patterns"]
heroImage: "https://raw.githubusercontent.com/HoangGeek/store/main/webp/FVUigNC.webp"
---

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

![Image](https://raw.githubusercontent.com/HoangGeek/store/main/webp/223170566-1d2c85ea-ff4e-4d03-a231-85640e916fd8.webp)

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

user Emp1 "Nhân viên 1 gọi PhoneLine()"
user Emp2 "Nhân viên 2 gọi PhoneLine()"
gateway Meta "PhoneLineSingleton.__call__ (Lock)" icon=python
service Line "1 đường dây PhoneLine duy nhất"

beat first "1. Lần đầu kết nối (mất 10s)":
  show $nodes stagger=50ms
  Emp1 -> Meta "PhoneLine()"
  Meta -> Line "Khóa _lock -> khởi tạo & cache"
  Emp1 <- Meta "Trả id(Line)"
  glow Meta color=#3b82f6

beat second "2. Lần sau dùng lại ngay":
  Emp2 -> Meta "PhoneLine()"
  Emp2 <- Meta "Trả đúng id(Line) đã cache"
  glow Line 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 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._

![Image](https://raw.githubusercontent.com/HoangGeek/store/main/webp/1*dQQDhdA785QZ6ukHZ2bSNg.webp)

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

``` python
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.

``` shell
talking on the 69 line
talking on the 69 line
```

## Triển khai Singleton:

### Cách viết không dùng Singleton:
``` python
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):
``` python
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](https://github.com/HoangYell/Design-Pattern-From-Simple-Things/blob/main/cp5_singleton.py)

***

**Điều hướng series:** Trước: [CP4 - Prototype](https://hoangyell.com/vi/cp4-prototype-learn-design-pattern-from-simple-things/) · Tiếp theo: [SP1 - Adapter](https://hoangyell.com/vi/sp1-adapter-learn-design-pattern-from-simple-things/)
