Bỏ qua đến nội dung

SP1 - Adapter (Cổng Chuyển Đổi) - Học Design Pattern Từ Những Thứ Đơn Giản

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

Hoang Yell
Hoang Yell
4 phút đọc
English
SP1 - Adapter (Cổng Chuyển Đổi) - Học Design Pattern Từ Những Thứ Đơn Giản

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

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:

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:

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

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

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


Điều hướng series: Trước: CP5 - Singleton · Tiếp theo: SP2 - Decorator & Closure

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