Bỏ qua đến nội dung

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.

Hoang Yell
Hoang Yell
4 phút đọc
English
BP2 - Chiến Thuật (Strategy) - Học Design Pattern Từ Những Thứ Đơn Giản

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óng pass_the_ball có thể đổi xoành xoạch giữa TikiTaka và CounterAttack 🔄.
"""
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.
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.

Source Code


Điều hướng series: Trước: BP1 - Gun (Iterator) · Tiếp theo: BP3 - Command

Bài viết liên quan

yell@hoangyell:~ %

>hoangyell --status

Đang bận chở vợ con đi cafe & chơi với AI ☕🤖

Ủa ai réo Yell đấy? Cần tâm sự chuyện code hay collab thì ghé Instagram tui nè:

Ghé Instagram esc to close