BP6 - Trạng Thái (State) - Học Design Pattern Từ Những Thứ Đơn Giản
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.

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.
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/elselồ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.
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:
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:
🤑 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):
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:
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.
Điều hướng series: Trước: BP5 - Observer · Tiếp theo: BP7 - Template Method
Bài viết liên quan
- Software Craft
BP11 - Máy Tính Mini (Interpreter) - Học Design Pattern Từ Những Thứ Đơn Giản
Biến biểu thức lồng nhau như (x + 10) - (y + 2) thành cây cú pháp tự tính toán kết quả theo từng ngữ cảnh. Học mẫu Interpreter trong Python.
5 phút đọcĐọc tiếp → - Software Craft
BP10 - Loa Phóng Thanh (Mediator) - Học Design Pattern Từ Những Thứ Đơn Giản
Sinh viên trong lớp không cần nhắn tin tay cho từng người một mà nói qua chiếc loa trung tâm. Học mẫu Mediator trong Python.
4 phút đọcĐọc tiếp → - Software Craft
BP9 - Lịch Sử File (Memento) - Học Design Pattern Từ Những Thứ Đơn Giản
Tính năng Undo nhìn qua tưởng đơn giản, nhưng bên dưới nó lưu và khôi phục trạng thái như thế nào? Tìm hiểu mẫu Memento bằng Python qua Photoshop.
5 phút đọcĐọc tiếp → - Software Craft
BP8 - Điệp Viên Thăm Dò (Visitor) - Học Design Pattern Từ Những Thứ Đơn Giản
Một điệp viên ghé thăm các cơ sở tuyệt mật để thu thập thông tin mà không cần đụng sửa class gốc. Học mẫu Visitor và double dispatch trong Python.
5 phút đọcĐọc tiếp →