首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 設計模式:迭代器模式迭代器介面與具體實作 (3/4)

     編輯:關於C語言

迭代器介面:IIterator

定義標準遍歷操作契約:

using System;
using System.Collections.Generic;
using System.Text;

namespace Pattern.Iterator
{
    /// 
    /// 迭代器介面(IIterator)
    /// 
    public interface IIterator
    {
        /// 
        /// 第一個物件
        /// 
        /// MessageModel
        MessageModel First();

        /// 
        /// 下一個物件
        /// 
        /// MessageModel
        MessageModel Next();

        /// 
        /// 當前物件
        /// 
        MessageModel CurrentMessageModel { get; }

        /// 
        /// 是否迭代完畢
        /// 
        bool IsDone { get; }
    }
}

具體迭代器:Iterator

實作遍歷邏輯,支援步長控制:

using System;
using System.Collections.Generic;
using System.Text;

namespace Pattern.Iterator
{
    /// 
    /// 迭代器(Iterator)
    /// 
    public class Iterator : IIterator
    {
        private Collection _collection;
        private int _current = 0;
        private int _step = 1;

        /// 
        /// 建構函式
        /// 
        /// 集合
        public Iterator(Collection collection)
        {
            this._collection = collection;
        }

        /// 
        /// 第一個物件
        /// 
        /// MessageModel
        public MessageModel First()
        {
            _current = 0;
            return _collection[_current];
        }

        /// 
        /// 下一個物件
        /// 
        /// MessageModel
        public MessageModel Next()
        {
            _current += _step;

            if (!IsDone)
            {
                return _collection[_current];
            }
            else
            {
                return null;
            }
        }

        /// 
        /// 當前物件
        /// 
        public MessageModel CurrentMessageModel
        {
            get { return _collection[_current]; }
        }

        /// 
        /// 是否迭代完畢
        /// 
        public bool IsDone
        {
            get { return _current >= _collection.Count ? true : false; }
        }

        /// 
        /// 步長
        /// 
        public int Step
        {
            get { return _step; }
            set { _step = value; }
        }
    }
}

Iterator 核心機制

  • 游標管理:_current 追蹤當前位置,_step 控制移動步長。
  • 集合引用:持有 Collection 參考,透過索引器存取元素。
  • 邊界檢查:IsDone 比較游標與 Count 判斷結束。
  • 靈活步長:Step 屬性支援跳躍式遍歷(如每隔 N 個元素)。

迭代器模式四大角色完整對應

.NET 內建 IEnumerable/IEnumerator 即是此模式標準實作,foreach 編譯器自動展開為迭代器模式調用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
模式角色本例類別說明
AggregateICollection抽象集合介面
ConcreteAggregateCollection具體集合,內部 List 管理元素
IteratorIIterator抽象迭代器介面
ConcreteIteratorIterator具體迭代器,游標遍歷邏輯