Bỏ qua đến nội dung

BP1 - Súng & Băng Đạn (Iterator) - Học Design Pattern Từ Những Thứ Đơn Giản

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.

Hoang Yell
Hoang Yell
4 phút đọc
English
BP1 - Súng & Băng Đạn (Iterator) - Học Design Pattern Từ Những Thứ Đơn Giản

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.

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.

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
# 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.
⬅️ Normal Gun 🔫:
🎯First Shoot: 1stBullet 
🎯The Rest: 2ndBullet-3rdBullet
🔄 LIFO Gun 🔫:
🎯First Shoot: 3rdBullet 
🎯The Rest: 2ndBullet-1stBullet

Triển khai Gun:

Cách viết ngắn dùng built-in iter():

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__):

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


Điều hướng series: Trước: SP7 - Proxy · Tiếp theo: BP2 - Strategy

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