[Specical] Design Pattern - Behavioral Patterns - Iterator Pattern
2016-07-05 08:03
363 查看
2007 |
Section 4, Chapter 3 |
Concept
Iterators allow sequential access of elements in a collection of objects without exposing its underlying code.
Use
If you have a list object and you wish to move through each element in the list sequentially and maintain your current place in the list, an iterator seems appropriate.
Design
Aggregate: a collection or aggregate object of some type whose elements we wish to iterate through.
Iterator: a tool to move through the aggregate elements and keep track of the progress.
Illustration
class List { private ArrayList _listItems = new ArrayList(); public Iterator CreateIterator() { return new Iterator(this); } public int Count { get{ return _listItems.Count; } } public void Append(object item) { _listItems.Add(item); } public void Remove(object item) { _listItems.Remove(item); } public void RemoveAt(int index) { _listItems.RemoveAt(index); } public object this[int index] { get{ return _listItems[index]; } set{ _listItems[index] = value; } } } class Iterator { private List _collection; private int _currentIndex = 0; private int _stepCount = 1; public Iterator(List collection) { this._collection = collection; } public int Step { get{ return _stepCount; } set{ _stepCount = value; } } public object First() { _currentIndex = 0; return _collection[_currentIndex]; } public object Next() { _currentIndex += _stepCount; if(!IsDone()) return _collection[_currentIndex]; else return null; } public object Last() { _currentIndex = _collection.Count - 1; return _collection[_currentIndex]; } public object Current() { return _collection[_currentIndex]; } public bool IsDone() { return _currentIndex >= _collection.Count ? true : false ; } }
Iterator skipIterator = list.CreateIterator(); skipIterator.Step = 3;
for(object item = skipIterator.First(); !skipIterator.IsDone(); item = skipIterator.Next())
相关文章推荐
- 大话西游之设计模式_起手篇
- 单例模式(Singleton Pattern)
- Design Pattern - Creational Patterns - Builder Pattern
- Design pattern--观察者模式
- OOD(object oriented design)
- Design Pattern - Structural Patterns - Bridge Pattern
- Design Pattern - Creational Patterns - Abstract Factory Pattern
- Design Pattern - Behavioral Patterns - Template Pattern
- Design Pattern - Structural Patterns - Facade Pattern
- Design Pattern - Structural Patterns - Composite Pattern
- 线程安全与效率的问题
- <Android 基础(十四)> selector
- 30分钟全面解析-SQL事务+隔离级别+阻塞+死锁
- 我的手机管家(10)病毒扫描 拷贝病毒数据库
- 【译文】城市相似性的可视化:美国和冰岛的相似之处
- 手动输入四位数 进行简单的加密运算
- Android基础--Android app应用多语言切换功能实现
- WPF中的binding(十二)- 多路Binding
- 前景检测算法(三)--帧差法
- 【投稿】Machine Learning With Spark Note 2:构建简单的推荐系统