---
title: "BP6 - Trạng Thái (State) - Học Design Pattern Từ Những Thứ Đơn Giản"
description: "Cây ATM xử lý hoàn toàn khác nhau tùy lúc chưa có thẻ, đã đút thẻ hay đã nhập đúng PIN. Học mẫu State trong Python để dẹp bỏ if/else lồng nhau."
pubDate: "2023-03-18"
lang: "vi"
slug: "bp6-state-learn-design-pattern-from-simple-things"
url: "https://hoangyell.com/vi/bp6-state-learn-design-pattern-from-simple-things/"
author: "HoangYell"
translation_en: "https://hoangyell.com/bp6-state-learn-design-pattern-from-simple-things/"
categories: ["Software Craft"]
tags: ["design-patterns", "behavioral-patterns"]
heroImage: "https://raw.githubusercontent.com/HoangGeek/store/main/webp/Oq4nHyi.webp"
---

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

## State là gì?

State (Finite State Machine - Máy trạng thái hữu hạn) tách các thao tác (`insert_card`, `eject_card`, `enter_pin`, `request_cash`) ra theo từng trạng thái riêng biệt (`no_card_state`, `has_card_state`, `has_correct_pin_state`):
- Chưa có thẻ (`no_card_state`): `insert_card`, `eject_card`, `enter_pin`, `request_cash`
- Đã đút thẻ (`has_card_state`): `insert_card`, `eject_card`, `enter_pin`, `request_cash`
- Đã nhập đúng PIN (`has_correct_pin_state`): `insert_card`, `eject_card`, `enter_pin`, `request_cash`

Mỗi class trạng thái tự xử lý tình huống hiện tại và tự chuyển `atm_machine.state` sang trạng thái hợp lệ tiếp theo khi cần.

![Image](https://raw.githubusercontent.com/HoangGeek/store/main/webp/226086072-4c6c68fc-9e7d-4885-a32b-e143520522bb.webp)

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

user User "Người rút tiền ATMMachine"
service NoCard "NoCardState"
service HasCard "HasCardState (wrong_pin_count)"
service PinOK "HasCorrectPinState"

beat flow "1. Đút thẻ & nhập đúng PIN":
  show $nodes stagger=50ms
  User -> NoCard "insert_card()"
  NoCard -> HasCard "state = has_card_state"
  HasCard -> PinOK "enter_pin(123456) -> request_cash()"
  glow PinOK color=#22c55e

beat reset "2. Nhả thẻ hoặc sai PIN 2 lần -> reset":
  PinOK -> NoCard "eject_card() -> wrong_pin_count = 0"
  HasCard -> NoCard "Sai PIN 2 lần -> eject_card()"
  glow NoCard color=#f59e0b

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 State?
- Cho phép một object đổi hẳn hành vi theo trạng thái bên trong của nó.
- Dẹp sạch đống `if/else` lồng nhau chằng chịt trong class chính (`ATMMachine`).
- Dễ thêm trạng thái mới mà không làm vỡ logic các trạng thái cũ.

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

**Đáp:** _Nếu chỉ có 2-3 trạng thái đơn giản, dùng thẳng `if/elif` hoặc `Enum` kết hợp dictionary chuyển trạng thái (`{(State.NO_CARD, "insert"): State.HAS_CARD}`) sẽ gọn hơn tạo cả loạt class. Chỉ nên tách class State khi mỗi trạng thái có logic dày và khác biệt ở nhiều method._

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

## Khi nào dùng State?

**Hỏi:** _Khi nào tôi nên dùng State?_

**Đáp:** _Khi hành vi của một object thay đổi hoàn toàn tùy theo trạng thái hiện tại, số lượng trạng thái nhiều và logic rẽ nhánh `if/else` bắt đầu trở thành ác mộng bảo trì._

### Đầu vào:
``` python
class NoCardState(ATMState):
    def insert_card(self):
        print("🏧 Card inserted")
        self.atm_machine.state = self.atm_machine.has_card_state

    def eject_card(self):
        print("🏧 No card to eject")

    def enter_pin(self, pin):
        print("🏧 Insert a card first")

    def request_cash(self):
        print("🏧 Insert a card first")

class HasCardState(ATMState):
    def insert_card(self):
        print("🏧 You cannot insert more than one card")

    def eject_card(self):
        print("🏧 Card ejected")
        self.atm_machine.wrong_pin_count = 0
        self.atm_machine.state = self.atm_machine.no_card_state

    def enter_pin(self, pin):
        if pin:
            print(f"🏧 Pin entered correctly: {pin}")
            self.atm_machine.state = self.atm_machine.has_correct_pin_state
        else:
            print("🏧 Wrong pin")
            self.atm_machine.wrong_pin_count += 1
            if self.atm_machine.wrong_pin_count >= 2:
                print("🏧 Too many wrong attempts")
                self.eject_card()

    def request_cash(self):
        print("🏧 Please enter your pin first")

class HasCorrectPinState(ATMState):
    def insert_card(self):
        print("🏧 You cannot insert more than one card")

    def eject_card(self):
        print("🏧 Card ejected\n")
        self.atm_machine.wrong_pin_count = 0
        self.atm_machine.state = self.atm_machine.no_card_state

    def enter_pin(self, pin):
        print("🏧 You already entered your pin")

    def request_cash(self):
        print("🏧 Cash dispensed 💵")
```
### Kết quả mong muốn:

``` shell
🤑 Request cash
🏧 Insert a card first
🤑 Insert card
🏧 Card inserted
🤑 Enter pin
🏧 Pin entered correctly: 123456
🤑 Request cash
🏧 Cash dispensed 💵
🤑 Eject card
🏧 Card ejected

🤑 Insert card
🏧 Card inserted
🤑 Enter pin
🏧 Wrong pin
🤑 Enter pin
🏧 Wrong pin
🏧 Too many wrong attempts
🏧 Card ejected
```

## Triển khai State:

### Cách viết không dùng State (`if/else` trong `ATMMachine`):

``` python
class ATMMachine:

    def __init__(self):
        self.card_inserted = False
        self.pin_entered = False
        self.wrong_pin_count = 0

    def insert_card(self):
        print("🤑 Insert card")
        if self.card_inserted:
            print("🏧 You cannot insert more than one card")
        else:
            print("🏧 Card inserted")
            self.card_inserted = True

    def eject_card(self):
        print("🤑 Eject card")
        if not self.card_inserted:
            print("🏧 No card to eject")
        else:
            print("🏧 Card ejected\n")
            self.card_inserted = False
            self.pin_entered = False
            self.wrong_pin_count = 0

    def enter_pin(self, pin):
        print("🤑 Enter pin")
        if not self.card_inserted:
            print("🏧 Insert a card first")
        else:
            if self.pin_entered:
                print("🏧 You already entered your pin")
            elif pin:
                print(f"🏧 Pin entered correctly: {pin}")
                self.pin_entered = True
            else:
                print("🏧 Wrong pin")
                self.wrong_pin_count += 1
                if self.wrong_pin_count >= 2:
                    print("🏧 Too many wrong attempts")
                    self.eject_card()

    def request_cash(self):
        print("🤑 Request cash")
        if not self.card_inserted:
            print("🏧 Insert a card first")
        elif not self.pin_entered:
            print("🏧 Please enter your pin first")
        else:
            print("🏧 Cash dispensed 💵")

if __name__ == "__main__":
    atm = ATMMachine()
    atm.request_cash()
    atm.insert_card()
    atm.enter_pin(123456)
    atm.request_cash()
    atm.eject_card()
    atm.insert_card()
    atm.enter_pin(None)
    atm.enter_pin(None)
```

### Cách viết dùng State:

``` python
class ATMState:
    def __init__(self, atm_machine):
        self.atm_machine = atm_machine

    def insert_card(self):
        pass

    def eject_card(self):
        pass

    def enter_pin(self, pin):
        pass

    def request_cash(self):
        pass

class NoCardState(ATMState):
    def insert_card(self):
        print("🏧 Card inserted")
        self.atm_machine.state = self.atm_machine.has_card_state

    def eject_card(self):
        print("🏧 No card to eject")

    def enter_pin(self, pin):
        print("🏧 Insert a card first")

    def request_cash(self):
        print("🏧 Insert a card first")

class HasCardState(ATMState):
    def insert_card(self):
        print("🏧 You cannot insert more than one card")

    def eject_card(self):
        print("🏧 Card ejected")
        self.atm_machine.wrong_pin_count = 0
        self.atm_machine.state = self.atm_machine.no_card_state

    def enter_pin(self, pin):
        if pin:
            print(f"🏧 Pin entered correctly: {pin}")
            self.atm_machine.state = self.atm_machine.has_correct_pin_state
        else:
            print("🏧 Wrong pin")
            self.atm_machine.wrong_pin_count += 1
            if self.atm_machine.wrong_pin_count >= 2:
                print("🏧 Too many wrong attempts")
                self.eject_card()

    def request_cash(self):
        print("🏧 Please enter your pin first")

class HasCorrectPinState(ATMState):
    def insert_card(self):
        print("🏧 You cannot insert more than one card")

    def eject_card(self):
        print("🏧 Card ejected\n")
        self.atm_machine.wrong_pin_count = 0
        self.atm_machine.state = self.atm_machine.no_card_state

    def enter_pin(self, pin):
        print("🏧 You already entered your pin")

    def request_cash(self):
        print("🏧 Cash dispensed 💵")

class ATMMachine:
    def __init__(self):
        self.no_card_state = NoCardState(self)
        self.has_card_state = HasCardState(self)
        self.has_correct_pin_state = HasCorrectPinState(self)

        self.state = self.no_card_state
        self.wrong_pin_count = 0

    def insert_card(self):
        print("🤑 Insert card")
        self.state.insert_card()

    def eject_card(self):
        print("🤑 Eject card")
        self.state.eject_card()

    def enter_pin(self, pin):
        print("🤑 Enter pin")
        self.state.enter_pin(pin)

    def request_cash(self):
        print("🤑 Request cash")
        self.state.request_cash()

if __name__ == "__main__":
    atm = ATMMachine()
    atm.request_cash()
    atm.insert_card()
    atm.enter_pin(123456)
    atm.request_cash()
    atm.eject_card()
    atm.insert_card()
    atm.enter_pin(None)
    atm.enter_pin(None)
```

Mỗi trạng thái (`NoCardState`, `HasCardState`, `HasCorrectPinState`) tự giữ luật chơi và chuyển tiếp `atm_machine.state` khi hợp lệ, dẹp sạch mớ `if/else` bên trong `ATMMachine`. Sau này cần thêm `OutOfServiceState` chỉ cần viết đúng 1 class mới.

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

***

**Điều hướng series:** Trước: [BP5 - Observer](https://hoangyell.com/vi/bp5-observer-learn-design-pattern-from-simple-things/) · Tiếp theo: [BP7 - Template Method](https://hoangyell.com/vi/bp7-template-method-learn-design-pattern-from-simple-things/)
