首页 > 其他分享 >设计模式之迭代器模式

设计模式之迭代器模式

时间:2022-10-06 14:11:59浏览次数:38  
标签:遍历 迭代 collection 模式 ._ position 设计模式 public

迭代器模式

概念

Iterator is a behavioral design pattern that lets you traverse elements of a collection without exposing its underlying representation (list, stack, tree, etc.).

迭代器模式是一种行为设计模式, 让你能在不暴露集合底层表现形式 (列表、 栈和树等) 的情况下遍历集合中所有的元素。

场景

当一个类内部有复杂的数据结构,有可能是链表、树、图等,使用者需要遍历这个类所有的成员的时候,可能会自己编写编写算法。

迭代器模式就是抽取接口,对外隐藏复杂的数据结构,仅仅提供一个简单的遍历接口的模式。

这种模式的好处是,遍历算法可能是复杂的,多样的。例如同样是树结构,也可以写出深度遍历和层次遍历两种不同的遍历算法。

迭代器模式就是封装多种不同类型的遍历算法,提供统一的接口,通常情况下,使用者可以获取当前元素,下一个元素,剩余的元素这些方法。

案例

先看一个简单的例子,这个类内部的数据结构是线性表,比较好遍历

 首先有这样一个集合,可以添加元素,提取元素等,集合本身不是先迭代的方法,内部会使用一个迭代器来迭代所有元素

为了满足这个要求,抽一个接口

    abstract class IteratorAggregate : IEnumerable
    {
        public abstract IEnumerator GetEnumerator();
    }

 

集合实现接口,并另外封装迭代器

class WordsCollection : IteratorAggregate
    {
        List<string> _collection = new List<string>();

        bool _direction = false;

        public void ReverseDirection()
        {
            _direction = !_direction;
        }

        public List<string> getItems()
        {
            return _collection;
        }

        public void AddItem(string item)
        {
            this._collection.Add(item);
        }

        public override IEnumerator GetEnumerator()
        {
            return new AlphabeticalOrderIterator(this, _direction);
        }
    }

 

现在开始实现迭代器

先定好接口

    abstract class Iterator : IEnumerator
    {
        object IEnumerator.Current => Current();
        public abstract int Key();
        public abstract object Current();
        public abstract bool MoveNext();
        public abstract void Reset();
    }

 

然后让迭代器实现接口,由于是线性表,接口实现起来很容易。

只需要记录一个指针,指向当前元素。如果需要下一个元素,就把指针往后头移动。如果反向便利,就把指针往前头移动。

class AlphabeticalOrderIterator : Iterator
    {
        private WordsCollection _collection;
        private int _position = -1;

        private bool _reverse = false;

        public AlphabeticalOrderIterator(WordsCollection collection, bool reverse = false)
        {
            this._collection = collection;
            this._reverse = reverse;

            if (reverse)
            {
                this._position = collection.getItems().Count;
            }
        }

        public override object Current()
        {
            return this._collection.getItems()[_position];
        }

        public override int Key()
        {
            return this._position;
        }

        public override bool MoveNext()
        {
            int updatedPosition = this._position + (this._reverse ? -1 : 1);

            if (updatedPosition >= 0 && updatedPosition < this._collection.getItems().Count)
            {
                this._position = updatedPosition;
                return true;
            }
            else
            {
                return false;
            }
        }

        public override void Reset()
        {
            this._position = this._reverse ? this._collection.getItems().Count - 1 : 0;
        }
    }

 

现在可以遍历集合了,注意c#语言实现IEnumerable接口的都可以写foreach

            var collection = new WordsCollection();
            collection.AddItem("First");
            collection.AddItem("Second");
            collection.AddItem("Third");

            Console.WriteLine("Straight traversal:");

            foreach (var element in collection)
            {
                Console.WriteLine(element);
            }

            Console.WriteLine("\nReverse traversal:");

            collection.ReverseDirection();

            foreach (var element in collection)
            {
                Console.WriteLine(element);
            }

 

下面来看一个复杂的案例,这个案例将会遍历树形结构

 

标签:遍历,迭代,collection,模式,._,position,设计模式,public
From: https://www.cnblogs.com/chenyingzuo/p/16757511.html

相关文章

  • JAVA设计模式-外观模式
    JAVA设计模式-外观模式介绍外观模式是一种结构型模式,主要是为了隐藏系统的复杂性,对外提供一个可以访问的接口,客户端只需要访问这个接口即可。例如:我们现在的智能家居中......
  • 设计模式-构造器模式
    封装复杂对象的构造逻辑,那么这讲的话呢,实际上是这个builder模式,这个构造器模式就是builder,ok,那么这个builder模式所要实现的是一个什么场景呢,就是,是这样的,比如说我们现在要......
  • Red Hat Enterprise Linux release 8.0 (Ootpa)-进入单用户模式重新设置root密码
    RedHatEnterpriseLinuxrelease8.0使用单用户模式有一个前提,即系统引导器(GRUB)能正常工作;否则,就要使用修复模式进行系统维护。需要注意的是,进入单用户模式后,如果没有开......
  • 设计模式之责任链模式
    责任链模式概念ChainofResponsibility isabehavioraldesignpatternthatletsyoupassrequestsalongachainofhandlers.Uponreceivingarequest,each......
  • 设计模式之命令模式
    命令模式概念Command isabehavioraldesignpatternthatturnsarequestintoastand-aloneobjectthatcontainsallinformationabouttherequest.Thistra......
  • 5-互评-OO之接口-DAO模式代码阅读及应用
    DAO模式是接口的一个典型应用。阅读附件中的参考代码,并回答以下问题:StudenDaoListImpl.java与StudentDaoArrayImpl.java有何不同?StudenDaoListImpl.java采用List存......
  • 分组密码的基本的工作模式、优缺点
    1、电子密码本ECB(Electroniccodebook)需要加密的消息按照块密码的块大小被分为数个块,并对每个块进行独立加密。适用于数据较少的情况,比如加密秘钥。优点:简单、快速、......
  • 设计模式-外观模式
    将多个内部模块的调用封装在一个类中。这个外观模式的化,它是facade模式,这个是它的一个英文名啊,那我们这边的话呢,还是一样啊,上来给大家举一个场景吧,这个场景啊,假设我们现在......
  • 一篇文章让你彻底理解Java的单例设计模式
    下文是笔者编写的单例模式实现的八种方式,如下所示:单例模式的简介我们将一个类在当前进程中只有一个实例的这种模式,称之为“单例模式”那么Java代码如何实现一个单例模式呢?......
  • JAVA设计模式-装饰模式
    JAVA设计模式-装饰模式介绍装饰模式是一种结构型模式,在不改变现有对象结构的前提下,给现有对象添加新的功能,动态增加职责,是现有类的一个包装。角色Component:定义一......