---
title: "SP5 - Mặt Tiền (Facade) - Học Design Pattern Từ Những Thứ Đơn Giản"
description: "Nhiều phòng ban nhưng chỉ cần một cửa đón tiếp. Mẫu Facade gom hệ thống rắc rối vào một giao diện gọn gàng trong Python."
pubDate: "2023-05-16"
lang: "vi"
slug: "sp5-facade-learn-design-pattern-from-simple-things"
url: "https://hoangyell.com/vi/sp5-facade-learn-design-pattern-from-simple-things/"
author: "HoangYell"
translation_en: "https://hoangyell.com/sp5-facade-learn-design-pattern-from-simple-things/"
categories: ["Software Craft"]
tags: ["design-patterns", "structural-patterns"]
heroImage: "https://raw.githubusercontent.com/HoangGeek/store/main/webp/photo-1587930610293-9585eec015ec.webp"
---

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

## Facade là gì?

Facade đặt một cánh cửa đơn giản trước cả một đống hệ thống con phức tạp. Bạn muốn vào tòa nhà làm việc thì chỉ cần đi qua sảnh chính thay vì tự tay quẹt thẻ bảo vệ, tự check-in lễ tân rồi tự bấm điều khiển thang máy từng bước một.

![Image](https://raw.githubusercontent.com/HoangGeek/store/main/webp/94cea254-1413-4465-9ad5-b218bdd12d33.webp)

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

user Nancy "Khách: Nancy"
gateway Facade "BuildingFacade.enter(1234, 'Nancy', 5)" icon=python
service Security "Security.check(1234)"
service Reception "Reception.greet('Nancy')"
service Elevator "Elevator.move(5)"

beat enter "1. Một cửa vào duy nhất":
  show $nodes stagger=50ms
  Nancy -> Facade "building.enter(...)"
  glow Facade color=#3b82f6

beat orchestrate "2. Tự điều phối các phòng ban":
  Facade -> Security "Kiểm tra thẻ -> True"
  Facade -> Reception "Chào khách tại sảnh"
  Facade -> Elevator "Đưa lên tầng 5"
  glow Elevator 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 Facade?
- **Gọn chỗ gọi**: Bên ngoài chỉ gọi `building.enter(...)` thay vì lặp lại đoạn khởi tạo `Security`, `Reception`, `Elevator` ở khắp mọi nơi.
- **Dễ sửa bên trong**: Đổi luồng xử lý nội bộ các subsystem mà không làm vỡ code caller.
- **Đánh đổi**: Dễ biến thành một "God object" ôm đồm nếu nhét quá nhiều thứ vào Facade; và việc khởi tạo cứng `self.elevator = Elevator()` bên trong `__init__` khiến unit test khó mock nếu không cho phép inject dependency tùy chọn.

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

**Hỏi:** _Tôi ghét Facade, có cách nào khác không?_

**Đáp:** _Gọi thẳng các subsystem nếu chỉ có một chỗ dùng tới chúng. Còn trong Python, đa số trường hợp bạn chẳng cần tạo `class BuildingFacade`: một hàm module `enter_building(...)` hoặc file `__init__.py` export sẵn API sạch sẽ chính là Facade tự nhiên nhất._

## Khi nào dùng Facade?
**Hỏi:** _Khi nào thì nên dùng Facade?_

**Đáp:** _Khi nhiều chỗ trong codebase phải lặp lại cùng một chuỗi thao tác qua 3+ class hoặc thư viện ngoài phức tạp và bạn muốn gom thành một điểm vào duy nhất._

### Đầu vào:
Ba class đại diện cho 3 hệ thống con trong tòa nhà: **Elevator**, **Security**, **Reception**.

``` python
# Subsystem classes
class Elevator:
    def move(self, floor):
        print(f"Moving to floor {floor}...")

class Security:
    def check(self, id):
        print(f"Checking id {id}...")
        return True

class Reception:
    def greet(self, name):
        print(f"Hello {name}, welcome to our building!")
```

### Kết quả mong muốn:
Giấu chi tiết từng hệ thống con đi, chỉ lộ ra một thao tác vào tòa nhà đơn giản:

``` shell
Checking id 1234...
Hello Nancy, welcome to our building!
Moving to floor 5...
```

## Triển khai Facade:

### Cách viết không dùng Facade:
``` python
if __name__ == "__main__":
    elevator = Elevator()
    security = Security()
    reception = Reception()
    if security.check(1234):
        reception.greet("Nancy")
        elevator.move(5)
```

### Cách viết dùng Facade:
``` python
# Facade class
class BuildingFacade:
    def __init__(self):
        self.elevator = Elevator()
        self.security = Security()
        self.reception = Reception()

    def enter(self, id, name, floor):
        if self.security.check(id):
            self.reception.greet(name)
            self.elevator.move(floor)

if __name__ == "__main__":
    building = BuildingFacade()
    building.enter(1234, "Nancy", 5)
```

`BuildingFacade.enter()` gói gọn cả `Security`, `Reception` và `Elevator` sau một lời gọi duy nhất. Trong dự án Python thực tế, `requests.get()` hay một file `package/__init__.py` gọn gàng cũng chính là áp dụng tư duy Facade mà không cần ép mình viết class.

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

***

**Điều hướng series:** Trước: [SP4 - Mixer (Bridge)](https://hoangyell.com/vi/sp4-mixer-learn-design-pattern-from-simple-things/) · Tiếp theo: [SP6 - Object Pool (Flyweight)](https://hoangyell.com/vi/sp6-object-pool-learn-design-pattern-from-simple-things/)
