---
title: "BP11 - Máy Tính Mini (Interpreter) - Học Design Pattern Từ Những Thứ Đơn Giản"
description: "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."
pubDate: "2023-05-09"
lang: "vi"
slug: "bp11-interpreter-learn-design-pattern-from-simple-things"
url: "https://hoangyell.com/vi/bp11-interpreter-learn-design-pattern-from-simple-things/"
author: "HoangYell"
translation_en: "https://hoangyell.com/bp11-interpreter-learn-design-pattern-from-simple-things/"
categories: ["Software Craft"]
tags: ["design-patterns", "behavioral-patterns"]
heroImage: "https://raw.githubusercontent.com/HoangGeek/store/main/webp/ai-bp11-interpreter-learn-design-pattern-from-simple-things-hero.webp"
---

_Máy Tính Mini (Interpreter) là một mẫu thiết kế nhóm **Behavioral**:_
🖤🖤🤍🤍🤍 *(Độ hữu dụng trong Python: 2/5)*

## Máy Tính Mini (Interpreter) là gì?

Interpreter gán cho từng thành phần trong một ngôn ngữ nhỏ (hoặc bộ quy tắc) một class riêng để cả biểu thức có thể tự đệ quy tính ra kết quả dựa trên dictionary `context`.

Ví dụ bạn muốn tính biểu thức `(x + 10) - (y + 2)` với `x = 5`, `y = 3`:
- **Terminal expression (nút lá)** (`Number`, `Variable`): trả thẳng giá trị số hoặc tra tên biến trong `context`.
- **Non-terminal expression (nút nhánh)** (`Add`, `Subtract`): gọi `.interpret(context)` ở hai nhánh trái/phải rồi cộng hoặc trừ lại.

```markdy
scene duration=18 layout=TB width=760 height=960
theme: light=doodle dark=nebula

user Ctx "context = {'x': 5, 'y': 3}"
service Root "Subtract (trái - phải)" icon=python
service Left "Add (x + 10)"
service Right "Add (y + 2)"
storage Leaves "Variable('x')=5, 10 | Variable('y')=3, 2"

beat eval "1. Đọc giá trị các nút lá từ context":
  show $nodes stagger=50ms
  Ctx -> Leaves "Tra x=5, y=3"
  Leaves -> Left "5 + 10 = 15"
  Leaves -> Right "3 + 2 = 5"
  glow Leaves color=#3b82f6

beat combine "2. Cộng trừ ngược lên gốc AST":
  Left -> Root "15"
  Right -> Root "5"
  Ctx <- Root "15 - 5 = 10"
  glow Root 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 Interpreter?
- **Xử lý lồng nhau sạch sẽ**: Khi đã dựng thành cây biểu thức (AST), các phép tính lồng nhiều tầng ngoặc `((x + 10) - (y + 2))` tự giải mượt mà, không vỡ như cắt chuỗi `split()`.
- **Dễ thêm phép toán mới**: Muốn thêm phép nhân `Multiply` chỉ cần viết thêm đúng một class mới mà không đụng vào `Add` hay `Subtract`.
- **Đánh đổi**: Mỗi quy tắc ngữ pháp đẻ ra một class. Nếu ngôn ngữ phình to quá vài chục luật, đống class Interpreter sẽ trở nên nặng nề khó bảo trì.

**Hỏi:** _Tôi ghét Interpreter, trong Python dùng gì thay thế?_

**Đáp:** _Ngoài đời thực, dev Python hiếm khi viết tay cả dàn class Interpreter kiểu GoF. Nếu chỉ đọc literal Python an toàn thì dùng `ast.literal_eval()`. Còn nếu làm DSL, bộ lọc query hay công thức phức tạp, dùng hẳn parser như `lark`, `pyparsing`, hoặc module `ast` có sẵn kèm visitor an toàn sẽ nhanh và sạch hơn nhiều._

## Khi nào dùng Interpreter?

**Hỏi:** _Khi nào tôi nên dùng Interpreter?_

**Đáp:** _Khi bạn có một bộ quy tắc nhỏ gọn hoặc biểu thức logic cố định (ví dụ filter tìm kiếm, công thức tính giá, máy tính mini) cần đánh giá lặp đi lặp lại trên nhiều bộ dữ liệu `context` khác nhau._

### Đầu vào:

Các biểu thức kết hợp số, biến (`x`, `y`), phép cộng và phép trừ, đánh giá với `context = {"x": 5, "y": 3}`.

```python
from abc import ABC, abstractmethod

class Expression(ABC):
    @abstractmethod
    def interpret(self, context: dict[str, int]) -> int:
        pass
```

### Kết quả mong muốn:

Tính giá trị của `(x + 10) - (y + 2)` lần lượt với `x = 5, y = 3` và `x = 20, y = 4`:

```shell
Result (x=5, y=3): 10
Result (x=20, y=4): 24
```

## Triển khai Interpreter:

### Cách viết không dùng Interpreter (cắt chuỗi thủ công):

Tách chuỗi bằng `split()` chỉ sống nổi với `"5 + 10"`, gặp dấu ngoặc hoặc lồng nhiều tầng là gãy ngay.

```python
def naive_eval(expr: str, context: dict[str, int]) -> int:
    tokens = expr.split()
    if len(tokens) != 3:
        raise ValueError(f"Unsupported nested expression: {expr}")

    def resolve(token: str) -> int:
        return context[token] if token in context else int(token)

    left, op, right = resolve(tokens[0]), tokens[1], resolve(tokens[2])
    if op == "+":
        return left + right
    if op == "-":
        return left - right
    raise ValueError(f"Unknown operator: {op}")

if __name__ == "__main__":
    print(naive_eval("x + 10", {"x": 5}))
    try:
        print(naive_eval("(x + 10) - (y + 2)", {"x": 5, "y": 3}))
    except ValueError as err:
        print(f"Error: {err}")
```

### Cách viết dùng Interpreter:

```python
from abc import ABC, abstractmethod

class Expression(ABC):
    @abstractmethod
    def interpret(self, context: dict[str, int]) -> int:
        pass

class Number(Expression):
    def __init__(self, value: int):
        self.value = value

    def interpret(self, context: dict[str, int]) -> int:
        return self.value

class Variable(Expression):
    def __init__(self, name: str):
        self.name = name

    def interpret(self, context: dict[str, int]) -> int:
        return context[self.name]

class Add(Expression):
    def __init__(self, left: Expression, right: Expression):
        self.left = left
        self.right = right

    def interpret(self, context: dict[str, int]) -> int:
        return self.left.interpret(context) + self.right.interpret(context)

class Subtract(Expression):
    def __init__(self, left: Expression, right: Expression):
        self.left = left
        self.right = right

    def interpret(self, context: dict[str, int]) -> int:
        return self.left.interpret(context) - self.right.interpret(context)

if __name__ == "__main__":
    # Build the expression tree for: (x + 10) - (y + 2)
    expression = Subtract(
        Add(Variable("x"), Number(10)),
        Add(Variable("y"), Number(2)),
    )

    print(f"Result (x=5, y=3): {expression.interpret({'x': 5, 'y': 3})}")
    print(f"Result (x=20, y=4): {expression.interpret({'x': 20, 'y': 4})}")
```

Một khi đã dựng xong cây biểu thức, bạn có thể tính lại cùng một công thức với hàng loạt `context` khác nhau mà không phải parse lại chuỗi. Trong dự án Python thực tế, hãy giữ tư duy cây biểu thức này nhưng kết hợp với `lark` hoặc module `ast` thay vì gõ tay cả rừng class.

***

**Điều hướng series:** Trước: [BP10 - Mediator](https://hoangyell.com/vi/bp10-mediator-learn-design-pattern-from-simple-things/)
