惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
Netflix TechBlog - Medium
J
Java Code Geeks
爱范儿
爱范儿
雷峰网
雷峰网
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 三生石上(FineUI控件)
H
Hackread – Cybersecurity News, Data Breaches, AI and More
B
Blog RSS Feed
Google DeepMind News
Google DeepMind News
Jina AI
Jina AI
The GitHub Blog
The GitHub Blog
I
InfoQ
月光博客
月光博客
博客园 - 聂微东
博客园 - Franky
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
博客园_首页
G
Google Developers Blog
Blog — PlanetScale
Blog — PlanetScale
L
LangChain Blog
罗磊的独立博客
Apple Machine Learning Research
Apple Machine Learning Research

博客园 - Charly

我的电影记录 再去听他的演唱会 学友12月29日广州演唱会 张学友十大粤语&十大国语金曲赏析 妈妈的第二次重生 随便谈谈最近参与的2个项目 中奖的幸运与不幸 设计模式学习笔记二十五——总结 Moss2007搜索服务配置,没有索引器和搜索配置页面报错问题解决 设计模式学习笔记二十四——Visitor模式 设计模式学习笔记二十三——TemplateMethod模式 设计模式学习笔记二十二——Strategy模式 设计模式学习笔记二十一——State模式 设计模式学习笔记二十——Memento模式 设计模式学习笔记十九——Observer模式 在MOSS 2007中调试WebPart 设计模式学习笔记十八——Mediator模式 设计模式学习笔记十六——Interpreter模式 设计模式学习笔记十五——Command模式
设计模式学习笔记十七——Iterator模式
Charly · 2007-07-26 · via 博客园 - Charly

动机:在软件系统构建过程中,集合对象内部结构常常变化各异。希望在不暴露其内部结构的同时,可以让客户程序透明地访问其中包含的元素,同时这种“透明遍历”也为“同一种算法在多种集合对象上进行操作”提供了可能。

场景:在.NET类库中,IEnumerable即为聚合对象接口,IEnumerator为迭代器接口,通过实现这两个接口来实现迭代器。

结构

代码

namespace DesignPattern.Iterator
{
    
public class MyCollection : IEnumerable
    
{
        
int[] items;

        
public MyCollection()
        
{
            items 
= new int[5{12345};
        }


        
public int[] Items
        
{
            
get
            
{
                
return items;
            }

        }


        
public IEnumerator GetEnumerator()
        
{
            
return new MyEnumerator(this);
        }

    }


    
public class MyEnumerator : IEnumerator
    
{
        
int index;
        MyCollection collection;

        
public MyEnumerator(MyCollection collection)
        
{
            
this.collection = collection;
        }

        
        
public object Current 
        
{
            
get
            
{
                
return collection.Items[index];
            }

        }

            
        
public bool MoveNext()
        
{
            index 
++;
            
return (index < collection.Items.GetLength(0));
        }

        
        
public void Reset()
        
{
            index 
= -1;
        }

    }

}

namespace DesignPattern.Iterator
{
    
public class Client
    
{
        
public int Sum()
        
{
            
int sum = 0;

            MyCollection collection 
= new MyCollection();
            MyEnumerator iterator 
= new MyEnumerator(collection);

            
while (iterator.MoveNext())
            
{
                sum 
+= Convert.ToInt32(iterator.Current);
            }


            
return sum;
        }

    }

}

 要点
      1、迭代抽象:本模式通过将对聚合对象的访问和遍历从聚合对象中分离出来并放入一个迭代器对象中,实现对聚合对象的透明访问。
      2、迭代多态:为遍历不同的聚合对象提供一个统一的接口,从而支持同样的算法在不同的聚合对象上进行操作。
      3、迭代器的健壮性考虑:遍历的同时更改迭代器所在的聚合结构,会导致问题。