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.

Gun (Iterator) là một mẫu thiết kế nhóm Behavioral (Hành vi): 🖤🖤🖤🖤🤍 (Độ hữu dụng trong Python: 4/5)
IteratorvàIterablelà 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ònBullets(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.
- Hàm
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.
- Hàm
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:
1stBullet2ndBullet3rdBullet
# nothing here
Kết quả mong muốn:
- Bắn đạn ra theo đúng thứ tự mong muốn:
Normal Gun: bắn1stBullettrước, rồi tới2ndBullet, 3rdBullet.LIFO Gun: bắn ngược3rdBullettrước, rồi tới2ndBullet, 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}"
)
Điều hướng series: Trước: SP7 - Proxy · Tiếp theo: BP2 - Strategy
Bài viết liên quan
- Software Craft
BP11 - Máy Tính Mini (Interpreter) - Học Design Pattern Từ Những Thứ Đơn Giản
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.
5 phút đọcĐọc tiếp → - Software Craft
BP10 - Loa Phóng Thanh (Mediator) - Học Design Pattern Từ Những Thứ Đơn Giản
Sinh viên trong lớp không cần nhắn tin tay cho từng người một mà nói qua chiếc loa trung tâm. Học mẫu Mediator trong Python.
4 phút đọcĐọc tiếp → - Software Craft
BP9 - Lịch Sử File (Memento) - Học Design Pattern Từ Những Thứ Đơn Giản
Tính năng Undo nhìn qua tưởng đơn giản, nhưng bên dưới nó lưu và khôi phục trạng thái như thế nào? Tìm hiểu mẫu Memento bằng Python qua Photoshop.
5 phút đọcĐọc tiếp → - Software Craft
BP8 - Điệp Viên Thăm Dò (Visitor) - Học Design Pattern Từ Những Thứ Đơn Giản
Một điệp viên ghé thăm các cơ sở tuyệt mật để thu thập thông tin mà không cần đụng sửa class gốc. Học mẫu Visitor và double dispatch trong Python.
5 phút đọcĐọc tiếp →