BP2 - Chiến Thuật (Strategy) - Học Design Pattern Từ Những Thứ Đơn Giản
Làm HLV bóng đá, đầu trận đá phòng ngự phản công rồi xoay sang Tiki-Taka giữa hiệp. Hiểu ngay mẫu Strategy và cách dùng hàm trong Python.

Strategy là một mẫu thiết kế nhóm Behavioral: 🖤🖤🖤🖤🖤 (Độ hữu dụng trong Python: 5/5)
Strategy là gì?
Strategy là kỹ thuật giúp bạn cắm và tháo nóng một khối logic (TikiTaka, CounterAttack) vào trong một object chính (FootballClub) lúc đang chạy.
Tại sao dùng Strategy?
- Thêm chiến thuật mới không cần đụng sửa code của
FootballClub. - Chỉ cắm đúng chiến thuật cần thiết tại thời điểm đó, code gọn và dễ đọc hơn hẳn đống
if/elif.
Hỏi: Tôi ghét Strategy, có cách nào khác không?
Đáp: Bạn hoàn toàn có thể nhét thẳng counter_attack_pass_the_ball và tiki_taka_pass_the_ball vào trong class FootballClub rồi rẽ nhánh if/elif, mỗi tội phình to class nhanh lắm!
Khi nào dùng Strategy?
Hỏi: Khi nào tôi dùng Strategy?
Đáp: Khi một object có nhiều cách xử lý khác nhau cho cùng một hành động và cần đổi qua lại linh hoạt theo từng tình huống.
Đầu vào:
- Có một đội bóng
FootballClub:- Có hành động
attack, trong đó cách chuyền bóngpass_the_ballcó thể đổi xoành xoạch giữaTikiTakavàCounterAttack🔄.
- Có hành động
"""
class FootballClub:
def attack(self):
formation = [
["LB", "CB", "CB", "CB"],
["LCM", "CDM", "RCM"],
["LW", "CF", "RW"],
]
...pass_the_ball...
"""
import random
from abc import ABC, abstractmethod
class Strategy(ABC):
name = ""
@abstractmethod
def pass_the_ball(self, formation):
pass
class TikiTaka(Strategy):
name = "TikiTaka"
def pass_the_ball(self, formation):
defenders = formation[0][:]
midfielder_forwards = [*formation[1], *formation[2]]
random.shuffle(defenders)
random.shuffle(midfielder_forwards)
return [*defenders, *midfielder_forwards]
class CounterAttack(Strategy):
name = "CounterAttack"
def pass_the_ball(self, formation):
defenders = random.choice(formation[0])
midfielders = random.choice(formation[1])
forwards = random.choice(formation[2])
return [defenders, midfielders, forwards]
Kết quả mong muốn:
- Đội bóng
FootballClubđổi chiến thuật mượt mà giữa trận:- Lúc đầu: đá
CounterAttack. - Lúc sau: chuyển sang
TikiTaka.
- Lúc đầu: đá
Manager: Hey team! apply CounterAttack
LB >> CDM >> RW >> GOAAAALLL!!!
Manager: Hey team! apply TikiTaka
CB >> CB >> LB >> CB >> CDM >> RCM >> RW >> LW >> LCM >> CF >> GOAAAALLL!!!
Triển khai Strategy:
Cách viết không dùng Strategy (if/elif trong class):
class FootballClub:
def __init__(self, strategy):
self._strategy = strategy
@property
def strategy(self):
return self._strategy
@strategy.setter
def strategy(self, strategy):
self._strategy = strategy
def attack(self):
formation = [
["LB", "CB", "CB", "CB"],
["LCM", "CDM", "RCM"],
["LW", "CF", "RW"],
]
result = []
if self._strategy == "TikiTaka":
result = self.tiki_taka_pass_the_ball(formation)
elif self._strategy == "CounterAttack":
result = self.counter_attack_pass_the_ball(formation)
result.append("GOAAAALLL!!!")
print(" >> ".join(result))
def tiki_taka_pass_the_ball(self, formation):
defenders = formation[0][:]
midfielder_forwards = [*formation[1], *formation[2]]
random.shuffle(defenders)
random.shuffle(midfielder_forwards)
return [*defenders, *midfielder_forwards]
def counter_attack_pass_the_ball(self, formation):
defenders = random.choice(formation[0])
midfielders = random.choice(formation[1])
forwards = random.choice(formation[2])
return [defenders, midfielders, forwards]
if __name__ == "__main__":
strategy = "CounterAttack"
football_club = FootballClub(strategy)
print(f"Manager: Hey team! apply {strategy}")
football_club.attack()
strategy = "TikiTaka"
print(f"Manager: Hey team! apply {strategy}")
football_club.strategy = strategy
football_club.attack()
Cách viết dùng Strategy:
class FootballClub:
def __init__(self, strategy):
self._strategy = strategy
@property
def strategy(self):
return self._strategy
@strategy.setter
def strategy(self, strategy):
self._strategy = strategy
def attack(self):
formation = [
["LB", "CB", "CB", "CB"],
["LCM", "CDM", "RCM"],
["LW", "CF", "RW"],
]
result = self._strategy.pass_the_ball(formation)
result.append("GOAAAALLL!!!")
print(" >> ".join(result))
if __name__ == "__main__":
strategy = CounterAttack()
football_club = FootballClub(strategy)
print(f"Manager: Hey team! apply {strategy.name}")
football_club.attack()
strategy = TikiTaka()
print(f"Manager: Hey team! apply {strategy.name}")
football_club.strategy = strategy
football_club.attack()
Ghi chú Python: Vì function trong Python là first-class object, bạn hoàn toàn có thể truyền thẳng một function làm strategy thay vì tạo cả cây class
Strategy(ABC)nếu chỉ có duy nhất một method.
Điều hướng series: Trước: BP1 - Gun (Iterator) · Tiếp theo: BP3 - Command
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 →