---
title: "BP2 - Chiến Thuật (Strategy) - Học Design Pattern Từ Những Thứ Đơn Giản"
description: "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."
pubDate: "2022-12-10"
lang: "vi"
slug: "bp2-strategy-learn-design-pattern-from-simple-things"
url: "https://hoangyell.com/vi/bp2-strategy-learn-design-pattern-from-simple-things/"
author: "HoangYell"
translation_en: "https://hoangyell.com/bp2-strategy-learn-design-pattern-from-simple-things/"
categories: ["Software Craft"]
tags: ["design-patterns", "behavioral-patterns"]
heroImage: "https://raw.githubusercontent.com/HoangGeek/store/main/webp/hc2bVac.webp"
---

_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.

![Image](https://raw.githubusercontent.com/HoangGeek/store/main/webp/206896998-acbc4566-86ba-4829-913e-facb1c2ce8de.webp)

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

user Coach "HLV đổi bài giữa trận"
service Club "FootballClub.attack()" icon=python
service Counter "CounterAttack.pass_the_ball()"
service Tiki "TikiTaka.pass_the_ball()"

beat first "1. Nhập cuộc đá CounterAttack":
  show $nodes stagger=50ms
  Coach -> Club "FootballClub(CounterAttack())"
  Club -> Counter "LB >> CDM >> RW >> GOAAAALLL!!!"
  glow Counter color=#f59e0b

beat second "2. Xoay sang TikiTaka lúc đang chạy":
  Coach -> Club "football_club.strategy = TikiTaka()"
  Club -> Tiki "Đan bóng ngắn >> GOAAAALLL!!!"
  glow Tiki 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 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!_

![Image](https://img-9gag-fun.9cache.com/photo/aogvMpm_700bwp.webp)

## 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` 🔄.

``` python
"""
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`.

``` shell
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):
``` python
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:
``` python
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](https://github.com/HoangYell/Design-Pattern-From-Simple-Things/blob/main/bp2_strategy.py)

***

**Điều hướng series:** Trước: [BP1 - Gun (Iterator)](https://hoangyell.com/vi/bp1-gun-iterator-design-pattern-from-simple-things/) · Tiếp theo: [BP3 - Command](https://hoangyell.com/vi/bp3-command-learn-design-pattern-from-simple-things/)
