Bỏ qua đến nội dung

SP4 - Máy Lai Giống (Bridge) - Học Design Pattern Từ Những Thứ Đơn Giản

Quản lý trang trại chó với đủ giống và kiểu lông mà không muốn đẻ ra hàng chục subclass lai ghép? Học mẫu Bridge (Mixer) bằng Python.

Hoang Yell
Hoang Yell
5 phút đọc
English
SP4 - Máy Lai Giống (Bridge) - Học Design Pattern Từ Những Thứ Đơn Giản

Mixer (Bridge) là một mẫu thiết kế nhóm Structural: 🖤🖤🖤🤍🤍 (Độ hữu dụng trong Python: 3/5)

Mixer (Bridge) là gì?

Mixer (Bridge) tách hai chiều biến đổi độc lập thành hai cây class riêng biệt thay vì nhồi hết tổ hợp vào cùng một cây kế thừa. Một bên (Dog) sẽ giữ tham chiếu tới bên còn lại (Coat) và ủy quyền xử lý bộ lông sang đó.

Giả sử bạn nuôi trại chó với nhiều giống (Labrador, Poodle) và nhiều kiểu lông (Curly, Straight). Nếu không tách ra, mỗi lần thêm giống mới hay kiểu lông mới là bạn phải đẻ thêm cả mớ subclass tổ hợp như LabradorCurly, LabradorStraight, PoodleCurly, PoodleStraight…

Tại sao dùng Mixer?

  • Chặn đứng bùng nổ M x N subclass: 5 giống chó + 4 kiểu lông = 9 class thay vì 20 class.
  • Ghép linh hoạt lúc chạy: Đổi Coat thoải mái mà không phải sửa class Dog.
  • Đánh đổi: Thêm một tầng gọi gián tiếp, nên nếu chỉ có 1 chiều thay đổi thực sự thì bỏ qua, truyền thẳng tham số hoặc hàm là đủ.

Hỏi: Tôi ghét Mixer, có cách nào khác không?

Đáp: Dùng kế thừa thuần (mỗi tổ hợp một class) vẫn ổn nếu bạn chỉ có 2-3 cặp cố định. Nếu chiều thứ hai chỉ là dữ liệu nhẹ chứ không phải cả hệ thống hành vi, truyền thẳng thuộc tính vào Dog.__init__ sẽ gọn hơn.

Khi nào dùng Mixer?

Hỏi: Khi nào thì tôi cần tới Mixer?

Đáp: Khi hai chiều nghiệp vụ cùng mở rộng độc lập và bạn muốn ghép chúng qua composition thay vì nhân bản M x N subclass.

Đầu vào:

Có hai nhánh class riêng biệt:

  • Nhánh giống chó (dogs): Labrador, Poodle, …
  • Nhánh kiểu lông (coats): Curly, Straight, …
from abc import ABC, abstractmethod


class Coat(ABC):
    @abstractmethod
    def shed(self):
        pass


class Dog(ABC):
    def __init__(self, coat):
        self.coat = coat

    @abstractmethod
    def bark(self):
        pass


class Labrador(Dog):
    def bark(self):
        print("The labrador barks loudly.")


class Poodle(Dog):
    def bark(self):
        print("The poodle barks softly.")


class Curly(Coat):
    def shed(self):
        print("The curly coat sheds little hair.")


class Straight(Coat):
    def shed(self):
        print("The straight coat sheds moderate hair.")

Kết quả mong muốn:

  • Dùng composition truyền một object Coat cụ thể vào object Dog,
  • Ủy quyền hàm shed() sang cho Coat xử lý.
The labrador barks loudly.
The straight coat sheds moderate hair.

The poodle barks softly.
The curly coat sheds little hair.

Triển khai Mixer:

Cách viết không dùng Mixer (M x N subclass):

class LabradorCurly:
    # A subclass that combines two aspects: labrador and curly
    def bark(self):
        print("The labrador barks loudly.")

    def shed(self):
        print("The curly coat sheds little hair.")


class LabradorStraight:
    # A subclass that combines two aspects: labrador and straight
    def bark(self):
        print("The labrador barks loudly.")

    def shed(self):
        print("The straight coat sheds moderate hair.")


class PoodleCurly:
    # A subclass that combines two aspects: poodle and curly
    def bark(self):
        print("The poodle barks softly.")

    def shed(self):
        print("The curly coat sheds little hair.")


class PoodleStraight:
    # A subclass that combines two aspects: poodle and straight
    def bark(self):
        print("The poodle barks softly.")

    def shed(self):
        print("The straight coat sheds moderate hair.")


if __name__ == "__main__":
    # Create a labrador with a straight coat
    lab_straight = LabradorStraight()
    lab_straight.bark()
    lab_straight.shed()

    # Create a poodle with a curly coat
    poo_curly = PoodleCurly()
    poo_curly.bark()
    poo_curly.shed()

Cách viết dùng Mixer (Bridge):

from abc import ABC, abstractmethod


class Dog(ABC):
    # Abstraction
    def __init__(self, coat):
        # Reference to an object of type Coat
        self.coat = coat

    @abstractmethod
    def bark(self):
        pass

    def shed(self):
        # Delegate to the Coat object
        self.coat.shed()


class Labrador(Dog):
    # Refined Abstraction
    def bark(self):
        print("The labrador barks loudly.")


class Poodle(Dog):
    # Refined Abstraction
    def bark(self):
        print("The poodle barks softly.")


class Coat(ABC):
    # Implementer
    @abstractmethod
    def shed(self):
        pass


class Curly(Coat):
    # Concrete Implementation
    def shed(self):
        print("The curly coat sheds little hair.")


class Straight(Coat):
    # Concrete Implementation
    def shed(self):
        print("The straight coat sheds moderate hair.")


if __name__ == "__main__":
    # Create a labrador with a straight coat
    lab_straight = Labrador(Straight())
    lab_straight.bark()
    lab_straight.shed()

    # Create a poodle with a curly coat
    poo_curly = Poodle(Curly())
    poo_curly.bark()
    poo_curly.shed()

Thay vì 4 subclass lai ghép (LabradorCurly, LabradorStraight, …), bạn chỉ giữ 2 class Dog và 2 class Coat rồi ghép qua composition. Sau này thêm Husky hay WireCoat chỉ cần viết đúng 1 class mới.

Source Code


Điều hướng series: Trước: SP3 - Tree (Composite) · Tiếp theo: SP5 - Facade

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