迭代器模式(Iterator)
生活随笔
收集整理的這篇文章主要介紹了
迭代器模式(Iterator)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
迭代器模式
一. 迭代器模式
1.1 定義
- 提供一種方法順序訪問一個集合對象中的各種元素,而又不暴露該對象的內部表示.
1.2 角色
- 抽象迭代器接口(Iterator).
- 具體迭代器(ConcreteIterator).
- 抽象聚合接口(Aggregate).
- 具體聚合(ConcreteAggregate).
二. 具體實現
1.1 創建抽象迭代器接口
public interface Iterator {Object next();boolean hasNext();}1.2 創建抽象聚合接口
public interface Aggregate {Iterator iterator();}1.3 創建具體聚合及具體迭代器
public class ConcreteAggregate implements Aggregate {@Overridepublic Iterator iterator() {return new ConcreteIterator();}private class ConcreteIterator implements Iterator {@Overridepublic Object next() {System.out.println("ConcreteIterator next ...");return null;}@Overridepublic boolean hasNext() {System.out.println("ConcreteIterator hasNext ....");return true;}}}1.4 調用
public static void main(String[] args) {Aggregate aggregate = new ConcreteAggregate();Iterator iterator = aggregate.iterator();if(iterator.hasNext()){iterator.next();}}1.5 輸出
ConcreteIterator hasNext ....ConcreteIterator next ...三. 優缺點
3.1 優點
- 簡化了聚合類的接口.
3.2 缺點
- 增加新的聚合類需要增加新的具體迭代器.
四. 源碼
https://github.com/Seasons20/DisignPattern.gitEND
總結
以上是生活随笔為你收集整理的迭代器模式(Iterator)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 3- OpenCV+TensorFlow
- 下一篇: centos 6 安装zabbix 3.