---
title: "BP1 - Súng & Băng Đạn (Iterator) - Học Design Pattern Từ Những Thứ Đơn Giản"
description: "Phân biệt rõ Iterable (Băng đạn) và Iterator (Khẩu súng) trong Python qua ví dụ lên đạn, bóp cò từng viên theo thứ tự xuôi hoặc ngược."
pubDate: "2022-11-17"
lang: "vi"
slug: "bp1-gun-iterator-design-pattern-from-simple-things"
url: "https://hoangyell.com/vi/bp1-gun-iterator-design-pattern-from-simple-things/"
author: "HoangYell"
translation_en: "https://hoangyell.com/bp1-gun-iterator-design-pattern-from-simple-things/"
categories: ["Software Craft"]
tags: ["design-patterns", "behavioral-patterns"]
heroImage: "https://raw.githubusercontent.com/HoangGeek/store/main/webp/1yD4V87.webp"
---

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

> `Iterator` và `Iterable` là hai khái niệm hay làm người mới lú nhất, nên mình đổi tên lại cho dễ nhớ: `Gun` (Khẩu súng) là **Iterator**, còn `Bullets` (Băng đạn) là **Iterable**.

## Gun và Bullets là gì?

- `Bullets` (Iterable) là hộp chứa cả băng đạn.
  - Hàm `def __iter__()` giúp sắp xếp đạn và phụ kiện để lắp thành khẩu súng sẵn sàng bắn.
- `Gun` (Iterator) là thứ thực sự bóp cò bắn ra từng viên một.
  - Hàm `def __next__()` chính là thao tác bóp cò bắn viên tiếp theo.

![Image](https://raw.githubusercontent.com/HoangGeek/store/main/webp/202880298-3a615160-fc79-47ac-a4f7-4c06b4ad4ebd.webp)

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

storage Bullets "Bullets (Iterable: [1st, 2nd, 3rd])"
gateway Iter "iter(bullets) -> __iter__()" icon=python
service Gun "Gun (Iterator: giữ _position)"
user Shooter "next(gun) -> __next__()"

beat load "1. Lắp băng đạn thành khẩu súng":
  show $nodes stagger=50ms
  Bullets -> Iter "Đưa vào __iter__()"
  Iter -> Gun "Tạo Gun(reverse=False/True)"
  glow Gun color=#3b82f6

beat fire "2. Bóp cò bắn từng viên":
  Shooter -> Gun "next(gun)"
  Shooter <- Gun "1stBullet -> 2ndBullet -> StopIteration"
  glow Shooter 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 Gun (Iterator)?
Bắn súng kiểm soát được đường đạn, dễ nâng cấp phụ kiện như ống ngắm, la bàn hay nòng giảm thanh về sau.

**Hỏi:** _Ném thẳng viên đạn bằng tay cũng trúng mục tiêu vậy, bày vẽ khẩu súng làm gì cho màu mè?_

**Đáp:** _Khi chỉ cần ném 1-2 viên thì ném tay cho nhanh, nhưng khi bạn cần gắn thêm plugin hay tùy chỉnh kiểu bắn (xuôi, ngược, lọc điều kiện) thì khẩu súng phát huy tác dụng ngay._

![Image](https://media.tenor.com/C_qUzONv4skAAAAC/bush-throw-stone-at.gif)

## Khi nào dùng Gun?

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

**Đáp:** _Khi bạn cần duyệt và bắn lần lượt từng viên đạn trong băng!_

### Đầu vào:
  - Có sẵn 3 viên đạn:
    - `1stBullet`
    - `2ndBullet`
    - `3rdBullet`
```python
# nothing here
```
### Kết quả mong muốn:
  - Bắn đạn ra theo đúng thứ tự mong muốn:
    - `Normal Gun`: bắn `1stBullet` trước, rồi tới `2ndBullet, 3rdBullet`.
    - `LIFO Gun`: bắn ngược `3rdBullet` trước, rồi tới `2ndBullet, 1stBullet`.
```shell
⬅️ Normal Gun 🔫:
🎯First Shoot: 1stBullet 
🎯The Rest: 2ndBullet-3rdBullet
🔄 LIFO Gun 🔫:
🎯First Shoot: 3rdBullet 
🎯The Rest: 2ndBullet-1stBullet
```
![Image](https://raw.githubusercontent.com/HoangGeek/store/main/webp/Zzrqrq2.webp)

## Triển khai Gun:

### Cách viết ngắn dùng built-in `iter()`:
```python
if __name__ == "__main__":
    bullets = []
    # Input 1: Having many bullets:
    bullets.append("1stBullet")
    bullets.append("2ndBullet")
    bullets.append("3rdBullet")

    gun = iter(bullets)
    first_fired_bullet = next(gun)
    remaining_bullets = "-".join(gun)
    # Expected Output 1: Firing bullets in expected order by: Normal Gun
    print(
        f"⬅️ Normal Gun 🔫:\n🎯First Shoot: {first_fired_bullet} \n🎯The Rest: {remaining_bullets}"
    )

    lifo_gun = iter(bullets[::-1])
    first_fired_bullet = next(lifo_gun)
    remaining_bullets = "-".join(lifo_gun)
    # Expected Output 2: Firing bullets in expected order by: LIFO Gun
    print(
        f"🔄 LIFO Gun 🔫:\n🎯First Shoot: {first_fired_bullet} \n🎯The Rest: {remaining_bullets}"
    )
```

### Cách viết tự cài đặt Iterable & Iterator (`__iter__` / `__next__`):
```python
from collections.abc import Iterable, Iterator

class Bullets(Iterable):
    def __init__(self, bullets=None):
        self._bullets = [] if bullets is None else bullets

    # to_normal_gun
    def __iter__(self):
        return Gun(self._bullets)

    def to_lifo_gun(self):
        return Gun(self._bullets, reverse=True)

    def load(self, bullet):
        self._bullets.append(bullet)

class Gun(Iterator):
    _position = None
    _reverse = False

    def __init__(self, bullets, reverse=False):
        self._bullets = bullets
        self._reverse = reverse
        self._position = -1 if reverse else 0

    def __next__(self):
        try:
            value = self._bullets[self._position]
            self._position += -1 if self._reverse else 1
        except IndexError:
            raise StopIteration()
        return value

if __name__ == "__main__":
    bullets = Bullets()
    # Input 1: Having many bullets:
    bullets.load("1stBullet")
    bullets.load("2ndBullet")
    bullets.load("3rdBullet")

    gun = iter(bullets)
    first_fired_bullet = next(gun)
    remaining_bullets = "-".join(gun)
    # Expected Output 1: Firing bullets in expected order by: Normal Gun
    print(
        f"⬅️ Normal Gun 🔫:\n🎯First Shoot: {first_fired_bullet} \n🎯The Rest: {remaining_bullets}"
    )

    lifo_gun = bullets.to_lifo_gun()
    first_fired_bullet = next(lifo_gun)
    remaining_bullets = "-".join(lifo_gun)
    # Expected Output 2: Firing bullets in expected order by: LIFO Gun
    # Note: In idiomatic Python, a generator using `yield` (or `reversed()`)
    # usually replaces writing a custom Iterator class by hand.
    print(
        f"🔄 LIFO Gun 🔫:\n🎯First Shoot: {first_fired_bullet} \n🎯The Rest: {remaining_bullets}"
    )
```

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

***

**Điều hướng series:** Trước: [SP7 - Proxy](https://hoangyell.com/vi/sp7-proxy-learn-design-pattern-from-simple-things/) · Tiếp theo: [BP2 - Strategy](https://hoangyell.com/vi/bp2-strategy-learn-design-pattern-from-simple-things/)
