XL: Iterator Design Pattern trong C# - Cách triển khai và ví dụ

Ngày đăng: 2023-05-05 12:15:13

Mục lục

1.Iterator Design Pattern trong C# là gì?

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ì.

2.Cách triển khai và ví dụ về Iterator Design Pattern trong C#

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

using System;

using System.Collections.Generic;

using System.Text;

 

namespace IteratorDesignPattern

{

    class Elempoyee

    {

        public int ID { get; set; }

        public string Name { get; set; }

        public Elempoyee(string name, int id)

        {

            Name = name;

            ID = id;

        }

    }

}

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

using System;

using System.Collections.Generic;

using System.Text;

 

namespace IteratorDesignPattern

{

    interface AbstractIterator

    {

        Elempoyee First();

        Elempoyee Next();

        bool IsCompleted { get; }

    }

}

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

using System;

using System.Collections.Generic;

using System.Text;

 

namespace IteratorDesignPattern

{

    class Iterator : AbstractIterator

    {

        private ConcreteCollection collection;

        private int current = 0;

        private int step = 1;

 

        public Iterator(ConcreteCollection collection)

        {

            this.collection = collection;

        }

        public Elempoyee First()

        {

            current = 0;

            return collection.GetEmployee(current);

        }

 

        public Elempoyee Next()

        {

            current += step;

            if (!IsCompleted)

            {

                return collection.GetEmployee(current);

            }

            else

            {

                return null;

            }

        }

        public bool IsCompleted

        {

            get { return current >= collection.Count; }

        }

    }

}

​​​​​​

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

using System;

using System.Collections.Generic;

using System.Text;

 

namespace IteratorDesignPattern

{

    interface AbstractCollection

    {

        Iterator CreateIterator();

    }

}

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

using System;

using System.Collections.Generic;

using System.Text;

 

namespace IteratorDesignPattern

{

    class ConcreteCollection : AbstractCollection

    {

        private List<Elempoyee> listEmployees = new List<Elempoyee>();

        //Create Iterator

        public Iterator CreateIterator()

        {

            return new Iterator(this);

        }

        // Gets item count

        public int Count

        {

            get { return listEmployees.Count; }

        }

        //Add items to the collection

        public void AddEmployee(Elempoyee employee)

        {

            listEmployees.Add(employee);

        }

        //Get item from collection

        public Elempoyee GetEmployee(int IndexPosition)

        {

            return listEmployees[IndexPosition];

        }

    }

}

Bước 6: Tạo class Program chạy chương trình và kiểm tra kết quả.

Program.cs

using System;

 

namespace IteratorDesignPattern

{

    class Program

    {

        static void Main(string[] args)

        {

            // Build a collection

            ConcreteCollection collection = new ConcreteCollection();

            collection.AddEmployee(new Elempoyee("Anurag", 100));

            collection.AddEmployee(new Elempoyee("Pranaya", 101));

            collection.AddEmployee(new Elempoyee("Santosh", 102));

            collection.AddEmployee(new Elempoyee("Priyanka", 103));

            collection.AddEmployee(new Elempoyee("Abinash", 104));

            collection.AddEmployee(new Elempoyee("Preety", 105));

            // Create iterator

            Iterator iterator = collection.CreateIterator();

            //looping iterator     

            Console.WriteLine("Iterating over collection:");

 

      for (Elempoyee emp = iterator.First(); !iterator.IsCompleted; emp = iterator.Next())

            {

                Console.WriteLine($"ID : {emp.ID} & Name : {emp.Name}");

            }

 

            Console.WriteLine("\n------------------------------------");

            Console.WriteLine("Chuong trinh nay duoc dang tai thuanhoaonline.com");

            Console.Read();

        }

    }

}

Kết quả:

 

Về bài trước...

                                  Bài tiếp theo...


Tài liệu lập trình C#

Bài viết trong cùng chuyên mục

Góc games giải trí



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



0379136392

Thông tin liên hệ: Lê Văn Thuyên - ĐT: 0379136392 ; Gmail: lethuyen0379136392@gmail.com

Comment

 +   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!

Trả lời

 *   Dũng Trung-090567448:Lê Văn Thuyên0379136392--->Ok.Anh!

Trả lời

 *   Bé Nguyễn-benguyen@gmail,com:Lê Văn Thuyên0379136392--->Good job!

Trả lời

 +   -:

Trả lời

 +   -:

Trả lời

12678