---
title: "SP4 - Máy Lai Giống (Bridge) - Học Design Pattern Từ Những Thứ Đơn Giản"
description: "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."
pubDate: "2023-05-13"
lang: "vi"
slug: "sp4-mixer-learn-design-pattern-from-simple-things"
url: "https://hoangyell.com/vi/sp4-mixer-learn-design-pattern-from-simple-things/"
author: "HoangYell"
translation_en: "https://hoangyell.com/sp4-mixer-learn-design-pattern-from-simple-things/"
categories: ["Software Craft"]
tags: ["design-patterns", "structural-patterns"]
heroImage: "https://raw.githubusercontent.com/HoangGeek/store/main/webp/F6oacm1.webp"
---

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

![Image](https://raw.githubusercontent.com/HoangGeek/store/main/webp/7b906c33-1d4e-46bd-b42f-2b12d5a41536.webp)

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

user Owner "Labrador(Straight())"
service DogAbs "Nhánh Dog (Labrador / Poodle)" icon=python
gateway Bridge "Tham chiếu self.coat"
service CoatImpl "Nhánh Coat (Curly / Straight)" icon=python

beat bark "1. Giống chó tự xử lý hành vi sủa":
  show $nodes stagger=50ms
  Owner -> DogAbs "lab_straight.bark()"
  glow DogAbs color=#3b82f6

beat shed "2. Ủy quyền rụng lông sang Coat":
  Owner -> DogAbs "lab_straight.shed()"
  DogAbs -> Bridge "gọi self.coat.shed()"
  Bridge -> CoatImpl "Lông thẳng rụng vừa phải"
  glow CoatImpl 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 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à đủ.

![Image](https://raw.githubusercontent.com/HoangGeek/store/main/webp/62665648042fe.webp)

**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`, ...

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

``` shell
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):
``` python
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):
``` python
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](https://github.com/HoangYell/Design-Pattern-From-Simple-Things/blob/main/sp4_mixer.py)

***

**Điều hướng series:** Trước: [SP3 - Tree (Composite)](https://hoangyell.com/vi/sp3-tree-learn-design-pattern-from-simple-things/) · Tiếp theo: [SP5 - Facade](https://hoangyell.com/vi/sp5-facade-learn-design-pattern-from-simple-things/)
