设计模式 - 迭代器模式
1.设计模式 - 工厂模式2.设计模式 - 抽象工厂模式3.设计模式 - 单例模式4.设计模式 - 建造者模式5.设计模式 - 原型模式6.设计模式 - 适配器模式7.设计模式 - 桥接模式8.设计模式 - 组合模式9.设计模式 - 装饰模式10.设计模式 - 外观模式11.设计模式 - 享元模式12.设计模式 - 代理模式13.设计模式 - 责任链模式14.设计模式 - 命令模式15.设计模式 - 解释器模式
16.设计模式 - 迭代器模式
17.设计模式 - 中介者模式18.设计模式 - 备忘录模式19.设计模式 - 观察者模式20.设计模式 - 状态模式21.设计模式 - 策略模式22.设计模式 - 模板方法模式23.设计模式 - 访问者模式24.设计模式合集概述
迭代器模式(Iterator Pattern)是一种行为型设计模式,它提供了一种方法顺序访问一个聚合对象中的各个元素,而又不需要暴露该对象的内部表示。迭代器模式通过引入迭代器对象来遍历聚合对象,使得客户端可以一致地访问聚合对象中的元素,而不需要了解其内部结构。
结构
迭代器模式包含以下几个角色:
- 迭代器(Iterator):定义访问和遍历元素的接口。
- 具体迭代器(ConcreteIterator):实现迭代器接口,负责遍历聚合对象中的元素。
- 聚合(Aggregate):定义创建迭代器对象的接口。
- 具体聚合(ConcreteAggregate):实现聚合接口,返回一个具体迭代器的实例。
示例代码
假设我们有一个应用程序需要遍历一个自定义的集合对象。
代码地址
迭代器接口
public interface IIterator<T>
{
bool HasNext();
T Next();
}
聚合接口
public interface IAggregate<T>
{
IIterator<T> CreateIterator();
}
具体聚合
public class CustomCollection<T> : IAggregate<T>
{
private readonly List<T> _items = [];
public void Add(T item)
{
_items.Add(item);
}
public IIterator<T> CreateIterator()
{
return new CustomIterator(this);
}
public int Count => _items.Count;
public T this[int index] => _items[index];
private class CustomIterator(CustomCollection<T> collection) : IIterator<T>
{
private int _currentIndex;
public bool HasNext()
{
return _currentIndex < collection.Count;
}
public T Next()
{
return collection[_currentIndex++];
}
}
}
客户端代码
class Program
{
static void Main(string[] args)
{
CustomCollection<string> collection = new CustomCollection<string>();
collection.Add("Item 1");
collection.Add("Item 2");
collection.Add("Item 3");
IIterator<string> iterator = collection.CreateIterator();
while (iterator.HasNext())
{
string item = iterator.Next();
Console.WriteLine(item);
}
}
}
应用场景
迭代器模式适用于以下场景:
- 访问聚合对象的内容:需要访问一个聚合对象的内容,而不需要暴露其内部表示时。
- 遍历不同的聚合结构:需要遍历不同的聚合结构,如列表、树、图等时。
- 统一的遍历接口:需要为不同的聚合结构提供一个统一的遍历接口时。
优缺点
优点
- 简化聚合类:迭代器模式将遍历聚合对象的职责分离到迭代器对象中,简化了聚合类的设计。
- 一致的遍历接口:迭代器模式为不同的聚合结构提供了一致的遍历接口,增加了系统的灵活性和可扩展性。
缺点
- 增加类的数量:迭代器模式引入了迭代器类,可能会增加系统中类的数量,增加系统的复杂性。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库