设计模式--迭代器模式(详解及C#示例)

含义:提供一种方法顺序访问一个聚合对象中的各种元素,而又不暴露该对象的内部表示。

优点:1.它支持以不同的方式遍历一个聚合对象。

           2.迭代器简化了聚合类。

           3.在同一个聚合上可以有多个遍历。

           4.在迭代器模式中,增加新的聚合类和迭代器类都很方便,无须修改原有代 码。

缺点:由于迭代器模式将存储数据和遍历数据的职责分离,增加新的聚合类需要对      应增加新的迭代器类,类的个数成对增加,这在一定程度上增加了系统的复杂性。

使用场景:1.访问一个聚合对象的内容而无须暴露它的内部表示。

                   2.需要为聚合对象提供多种遍历方式。

                   3.为遍历不同的聚合结构提供一个统一的接口。

C#示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IteratorPattern
{
    /// <summary>
    /// 顺序遍历接口
    /// </summary>
    public interface Iterator
    {
        bool hasNext();
        Object next();
    }
    /// <summary>
    /// 返回迭代器的接口
    /// </summary>
    public interface Container
    {
        Iterator getIterator();
    }
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IteratorPattern
{
    public class NameRepository : Container
    {
        public static String[] names = { "Robert", "John", "Julie", "Lora" };


        public Iterator getIterator()
        {
            return new NameIterator();
        }

        private class NameIterator : Iterator
        {

            int index;
            public bool hasNext()
            {
                if (index < names.Length)
                {
                    return true;
                }
                return false;
            }


            public Object next()
            {
                if (this.hasNext())
                {
                    return names[index++];
                }
                return null;
            }
        }
    }
}

 

执行部分:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace IteratorPattern
{
    public partial class Form1 : Form
    {
        NameRepository namesRepository;
        public Form1()
        {
            InitializeComponent();
            namesRepository = new NameRepository();
        }      
        private void button1_Click(object sender, EventArgs e)
        {
            for (Iterator iter = namesRepository.getIterator(); iter.hasNext(); )
            {
                String name = (String)iter.next();
                listBox1.Items.Add("Name : " + name);
            }
        }
    }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值