---
title: "SP1 - Adapter (Cổng Chuyển Đổi) - Học Design Pattern Từ Những Thứ Đơn Giản"
description: "Quá nhiều thiết bị cắm vào MacBook khiến bàn làm việc ngập dây cáp. Học cách dùng mẫu Adapter trong Python chỉ bằng vài dòng __getattr__."
pubDate: "2022-10-15"
lang: "vi"
slug: "sp1-adapter-learn-design-pattern-from-simple-things"
url: "https://hoangyell.com/vi/sp1-adapter-learn-design-pattern-from-simple-things/"
author: "HoangYell"
translation_en: "https://hoangyell.com/sp1-adapter-learn-design-pattern-from-simple-things/"
categories: ["Software Craft"]
tags: ["design-patterns", "structural-patterns"]
heroImage: "https://raw.githubusercontent.com/HoangGeek/store/main/webp/vTFProK.webp"
---

_Adapter là một mẫu thiết kế nhóm **Structural (Cấu trúc)**:_
🖤🖤🖤🖤🖤 *(Độ hữu dụng trong Python: 5/5)*

## Adapter là gì?

Adapter giống như một cục hub chuyển đổi (`USB-B sang USB-C`, `USB-A sang USB-C`, `HDMI sang USB-C`).

Nó giúp thiết bị chính (`MacBook` chỉ có cổng USB-C) kết nối trơn tru với đủ thứ không tương thích (`Printer`, `Flash`, `Monitor`).

![Image](https://raw.githubusercontent.com/HoangGeek/store/main/webp/202238106-a587babd-e4c6-4435-a6e5-8691d8215620.webp)

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

client Mac "MacBook (chỉ có USB-C: .connect())"
gateway Hub "Adapter (__dict__.update + __getattr__)" icon=python
service Printer "Printer (connect_usb_b)"
service Flash "Flash (connect_usb_a)"
service Monitor "Monitor (connect_hdmi)"

beat wrap "1. Gọi thống nhất qua USB-C":
  show $nodes stagger=50ms
  Mac -> Hub "device.connect()"
  glow Hub color=#3b82f6

beat dispatch "2. Chuyển đúng cổng từng thiết bị":
  Hub -> Printer "connect_usb_b() -> Printing..."
  Hub -> Flash "connect_usb_a() -> Copying..."
  Hub -> Monitor "connect_hdmi() -> Displaying..."
  glow Printer color=#22c55e
  glow Flash color=#22c55e
  glow Monitor 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 nên dùng Adapter?
Tất cả gom vào một cục chuyển đổi duy nhất, gọn gàng sạch sẽ.

_Khi dùng Adapter:_
![Image](https://raw.githubusercontent.com/HoangGeek/store/main/webp/section-4-mobile-v2.webp)

**Hỏi:** _Tôi ghét dùng cục Adapter tổng hợp, có cách nào khác không?_

**Đáp:** _Bạn hoàn toàn có thể mua từng sợi cáp chuyển đổi rời (`USB-B sang C`, `USB-A sang C`, `HDMI sang C`) để thay thế, nhìn bàn làm việc sẽ giống thế này:_

_Khi dùng cả đống dây chuyển rời:_
![Image](https://raw.githubusercontent.com/HoangGeek/store/main/webp/EUq9YdUU4AA6Mfi.webp)

## Khi nào dùng Adapter?
**Hỏi:** _Khi nào thì tôi cần một chiếc `USB type C Adapter`?_

**Đáp:** _Khi bạn cần cắm `Printer`, `Flash` hoặc `Monitor` vào `MacBook`, đúng chứ?_

### Đầu vào:
  - Một chiếc MacBook chỉ có duy nhất cổng USB-C.
  - Các thiết bị ngoại vi không dùng cổng USB-C:
    - `Printer (USB type B)`
    - `Flash (USB type A)`
    - `Monitor (HDMI)`
``` python
# Input 2: Having incompatible (non-USB type C) devices:
class Printer:
    name = "Printer"

    def connect_usb_b(self):
        return f"{self.name} is connected: Printing..."

# Input 2: Having incompatible (non-USB type C) devices:
class Flash:
    name = "Flash"

    def connect_usb_a(self):
        return f"{self.name} is connected: Copying..."

# Input 2: Having incompatible (non-USB type C) devices:
class Monitor:
    name = "Monitor"

    def connect_hdmi(self):
        return f"{self.name} is connected: Displaying..."
```
### Kết quả mong muốn:
  - Biến cả 3 thiết bị kia dùng chung một cổng gọi `connect()` chuẩn USB-C:
    - `Printer (USB type C)`
    - `Flash (USB type C)`
    - `Monitor (USB type C)`
  - MacBook kết nối được hết đám thiết bị đó qua cùng một vòng lặp.
``` shell
Printer is connected: Printing...
Flash is connected: Copying...
Monitor is connected: Displaying...
```

## Triển khai Adapter:

### Cách viết không dùng Adapter:
``` python
if __name__ == "__main__":
    devices = [Printer(), Flash(), Monitor()]
    for device in devices:
        if isinstance(device, Printer):
            # Expected Output 2: MacBook is able to connect to those incompatible devices
            print(device.connect_usb_b())
        elif isinstance(device, Flash):
            # Expected Output 2: MacBook is able to connect to those incompatible devices
            print(device.connect_usb_a())
        elif isinstance(device, Monitor):
            # Expected Output 2: MacBook is able to connect to those incompatible devices
            print(device.connect_hdmi())
```

### Cách viết dùng Adapter (Python `__getattr__`):
``` python
class Adapter:
    def __init__(self, obj, **adapted_methods):
        self.obj = obj
        self.__dict__.update(adapted_methods)

    def __getattr__(self, attr):
        return getattr(self.obj, attr)

# Note: __dict__.update + __getattr__ is concise in Python,
# though it trades off static type checking and IDE autocomplete.

if __name__ == "__main__":
    devices = []
    printer = Printer()
    # Expected Output 1: Making that non-USB type C devices have USB type C port
    devices.append(Adapter(printer, connect=printer.connect_usb_b))
    flash = Flash()
    # Expected Output 1: Making that non-USB type C devices have USB type C port
    devices.append(Adapter(flash, connect=flash.connect_usb_a))
    monitor = Monitor()
    # Expected Output 1: Making that non-USB type C devices have USB type C port
    devices.append(Adapter(monitor, connect=monitor.connect_hdmi))
    for device in devices:
        # Expected Output 2: MacBook is able to connect to those incompatible devices
        print(device.connect())
```

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

***

**Điều hướng series:** Trước: [CP5 - Singleton](https://hoangyell.com/vi/cp5-singleton-learn-design-pattern-from-simple-things/) · Tiếp theo: [SP2 - Decorator & Closure](https://hoangyell.com/vi/sp2-decorator-function-decorator-closure-learn-design-pattern-from-simple-things/)
