Mục lục
Iterator Design Pattern cho phép truy cập tuần tự các phần tử mà không để lộ logic bên trong.
Điều đó có nghĩa là bằng cách chúng ta sử dụng Iterator Design Pattern chúng ta có thể truy cập các phần tử của đối tượng. Và quá trình truy cập được thực hiện một cách tuần tự mà không cần biết các biểu diễn bên trong của nó.
Ví dụ: Chúng ta sử dụng iterators khá nhiều trong cuộc sống hàng ngày. Ví dụ điều khiển từ xa của TV. Bất kỳ điều khiển từ xa nào mà chúng ta sử dụng, chỉ cần cầm điều khiển và nhấn nút lên, xuống mà không cần biết logic bên trong nó là gì.
Trong phần này mình sẽ thực hiện triển khai Iterator Design Pattern trong C# thông qua một ví dụ cụ thể như sau.
Giả sử chúng ta có một tập hợp các nhân viên. Sau đó, chúng ta có thể dễ dàng lặp qua bộ sưu tập bằng cách sử dụng vòng lặp for hoặc for each.
Bây giờ mình sẽ thực hiện theo từng bước, các bạn có thể theo dõi nhé !!!
Bước 1: Tạo class Elempoyee.
Trong class có các thuộc tính: ID, Name và constructow Elempoyee.
Elempoyee.cs
|
Bước 2: Tạo interface AbstractIterator.
Class này định nghĩa một interface để truy cập và duyệt qua các phần tử.
AbstractIterator.cs
|
Bước 3: Tạo class Iterator.
Class này thực hiện giao diện AbstractIterator cũng như theo dõi vị trí hiện tại trong quá trình duyệt các phần tử.
Iterator.cs
|
Bước 4: Tạo interface AbstractCollection.
Class này định nghĩa một interface để tạo một đối tượng Iterator.
AbstractCollection.cs
|
Bước 5: Tạo class IteratorDesignPattern.
Class này triển khai interface AbstractCollection để trả về một instance của class Iterator.
ConcreteCollection.cs
|
Bước 6: Tạo class Program chạy chương trình và kiểm tra kết quả.
Program.cs
|
Kết quả:
Về bài trước... |
Bài tiếp theo... |
Cờ caro |
Butterfly |
Lật hình (luyện trí nhớ) |
Cờ tướng ONLINE |
Xếp hình |
Ghép hình |
15_PUZZLE |
Kill ghosts |
Banchim |
Planet Defense |
Tower game |
Tower game |
Plapy Bird (NH.Đông) |
Vượt chướng ngại vật |
+ Lê Văn Thuyên-0379136392:Cảm ơn quý vị và các bạn đã vào Website của Lê Thuyên! Lê thuyên rất mong nhận được sự góp ý của quý vị và các bạn cho sự phát triển của website này. Xin chân thành cảm ơn!
* Dũng Trung-090567448:Lê Văn Thuyên0379136392--->Ok.Anh!
* Bé Nguyễn-benguyen@gmail,com:Lê Văn Thuyên0379136392--->Good job!
+ -:
+ -: