banner
Jul 24, 2023
175 Views

Iterator pattern

Written by
banner

The iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements. The iterator pattern decouples algorithms from containers; in some cases, algorithms are necessarily container-specific and thus cannot be decoupled.

Mẫu Iterator là một mẫu thiết kế trong đó một bộ lặp được sử dụng để duyệt qua một bộ chứa và truy cập các phần tử của bộ chứa đó. Mẫu Iterator giải trừ sự ràng buộc giữa các thuật toán và các bộ chứa; trong một số trường hợp, các thuật toán đòi hỏi phải đặc thù cho từng bộ chứa và do đó không thể được giải trừ khỏi nhau.

Ví dụ

class Student:
    def __init__(self, name, age, grade):
        self.name = name
        self.age = age
        self.grade = grade

class Classroom:
    def __init__(self):
        self.students = []
    
    def add_student(self, student):
        self.students.append(student)
    
    def __iter__(self):
        return ClassroomIterator(self)

class ClassroomIterator:
    def __init__(self, classroom):
        self.classroom = classroom
        self.index = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.index < len(self.classroom.students):
            student = self.classroom.students[self.index]
            self.index += 1
            return student
        else:
            raise StopIteration()

# Tạo đối tượng lớp học
classroom = Classroom()

# Thêm các sinh viên vào lớp
classroom.add_student(Student("John", 20, "A"))
classroom.add_student(Student("Alice", 19, "B"))
classroom.add_student(Student("Bob", 21, "C"))

# Duyệt qua danh sách sinh viên bằng Iterator
for student in classroom:
    print(f"Name: {student.name}, Age: {student.age}, Grade: {student.grade}")

"""OUTPUT
Name: John, Age: 20, Grade: A
Name: Alice, Age: 19, Grade: B
Name: Bob, Age: 21, Grade: C
"""
Article Tags:
· · · ·
Article Categories:
dev
banner

Leave a Reply

Your email address will not be published. Required fields are marked *