---
title: "BP3 - Mệnh Lệnh (Command) - Học Design Pattern Từ Những Thứ Đơn Giản"
description: "Làm chỉ huy quân đội, bạn đóng gói từng nhiệm vụ và quân lính thành các gói lệnh lên kế hoạch sẵn để kích hoạt sau. Tìm hiểu mẫu Command trong Python."
pubDate: "2023-01-14"
lang: "vi"
slug: "bp3-command-learn-design-pattern-from-simple-things"
url: "https://hoangyell.com/vi/bp3-command-learn-design-pattern-from-simple-things/"
author: "HoangYell"
translation_en: "https://hoangyell.com/bp3-command-learn-design-pattern-from-simple-things/"
categories: ["Software Craft"]
tags: ["design-patterns", "behavioral-patterns"]
heroImage: "https://raw.githubusercontent.com/HoangGeek/store/main/webp/DFNtAdt.webp"
---

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

## Command là gì?

Command là kỹ thuật để người chỉ huy (`commander`) đóng gói toàn bộ thông tin cần thiết (`resource`, `soldier`) vào một object lệnh riêng biệt, để dành đó và kích hoạt thực thi ở một thời điểm sau.

![Image](https://raw.githubusercontent.com/HoangGeek/store/main/webp/212450729-1c2126ad-f09a-4c84-b286-6ef5d74e4c57.webp)

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

user Commander "Commander (lên kế hoạch trước, chạy sau)"
queue Cmd1 "NonSoldierCommand(payload)"
queue Cmd2 "SoldierCommand(soldier, resource)"
service Soldier "Soldier.do_something()"

beat queue "1. Đóng gói nhiệm vụ thành Command":
  show $nodes stagger=50ms
  Commander -> Cmd1 "init_first_command()"
  Commander -> Cmd2 "init_last_command()"
  glow Commander color=#3b82f6

beat exec "2. Phát lệnh thực thi về sau":
  Commander -> Cmd1 "execute()"
  Commander -> Cmd2 "execute()"
  Cmd2 -> Soldier "do_something(resource)"
  glow Soldier 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 Command?
- Cấu trúc rõ ràng, dễ xếp hàng đợi (queue), trì hoãn thực thi hoặc bổ sung logic mới mà không làm rối code người ra lệnh.

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

**Đáp:** _Cứ code bình thường và bỏ qua pattern này. Trong Python mọi thứ đều là object, nên bạn lưu callback (`lambda`, `functools.partial`) vào list rồi chạy sau cũng dễ ợt._

![Image](https://raw.githubusercontent.com/HoangGeek/store/main/webp/so-youre-telling-8e0c49466e.webp)

## Khi nào dùng Command?

**Hỏi:** _Khi nào tôi cần dùng Command?_

**Đáp:** _Khi bạn có nhiều tác vụ cần lưu trữ, lên lịch, đưa vào hàng đợi rồi mới kích hoạt chạy sau theo đúng kế hoạch._

### Đầu vào:
  - Có các tài nguyên (`Resource for the First Task`, `Resource for the Main Task`, `Resource for the Last Task`).
  - Có chuỗi tác vụ theo thứ tự `first_task`, `main_task`, `last_task`:

``` python
# nothing here
```
### Kết quả mong muốn:
  - Tài nguyên được đóng gói vào đúng task từ trước, rồi mới kích hoạt chạy khi chỉ huy phát lệnh.

``` shell
Commander: the first task is:
    💣NonSoldierCommand.executing: (Resource for the First Task)
Commander: the main task is:
    🧨Commander.executing: (Resource for the Main Task)
Commander: the last task is:
    💣SoldierCommand.executing: (<class '__main__.Soldier'>, Resource for the Last Task)
        Soldier.do_something with: (Resource for the Last Task)
```

## Triển khai Command:

### Cách viết không dùng Command (gọi thẳng tại chỗ):
``` python
def non_soldier_command_execute(payload):
    print(f"    💣NonSoldierCommand.executing: ({payload})")

def soldier_command_execute(soldier, resource):
    print(f"    💣SoldierCommand.executing: ({type(soldier)}, {resource})")
    soldier.do_something(resource)

class Soldier:
    def do_something(self, resource):
        print(f"        Soldier.do_something with: ({resource})")

if __name__ == "__main__":
    # no planning here, just do everything at once
    print("Commander: the first task is:")
    non_soldier_command_execute("Resource for the First Task")

    print("Commander: the main task is:")
    print(f"    🧨Commander.executing: (Resource for the Main Task)")

    print("Commander: the last task is:")
    soldier = Soldier()
    soldier_command_execute(soldier, "Resource for the Last Task")
```

### Cách viết dùng Command:
``` python
from abc import ABC, abstractmethod

class Command(ABC):
    @abstractmethod
    def execute(self):
        pass

class NonSoldierCommand(Command):
    def __init__(self, payload):
        self._payload = payload

    def execute(self):
        print(f"    💣NonSoldierCommand.executing: ({self._payload})")

class SoldierCommand(Command):
    def __init__(self, soldier, resource):
        self._soldier = soldier
        self._resource = resource

    def execute(self):
        print(f"    💣SoldierCommand.executing: ({type(self._soldier)}, {self._resource})")
        self._soldier.do_something(self._resource)

class Soldier:
    def do_something(self, resource):
        print(f"        Soldier.do_something with: ({resource})")

class Commander:
    _first_task = None
    _last_task = None

    def init_first_command(self, command):
        self._first_task = command

    def init_last_command(self, command):
        self._last_task = command

    def execute_main_command(self):
        print("Commander: the first task is:")
        if isinstance(self._first_task, Command):
            self._first_task.execute()

        print("Commander: the main task is:")
        print(f"    🧨Commander.executing: (Resource for the Main Task)")

        print("Commander: the last task is:")
        if isinstance(self._last_task, Command):
            self._last_task.execute()

if __name__ == "__main__":
    commander = Commander()

    # commander init: a command encapsulating needed information(resource) to execute the task at a later time.
    non_soldier_command = NonSoldierCommand("Resource for the First Task")
    commander.init_first_command(non_soldier_command)

    # commander init: a command encapsulating needed information(soldier, resource) to execute the task at a later time.
    soldier = Soldier()
    soldier_command = SoldierCommand(soldier, "Resource for the Last Task")
    commander.init_last_command(soldier_command)

    # after planning, this is the later time, time to execute the tasks initiated by the commander
    commander.execute_main_command()
```

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

***

**Điều hướng series:** Trước: [BP2 - Strategy](https://hoangyell.com/vi/bp2-strategy-learn-design-pattern-from-simple-things/) · Tiếp theo: [BP4 - Handling Chain](https://hoangyell.com/vi/bp4-handling-chain-learn-design-pattern-from-simple-things/)
