迭代器模式(Iterator)

迭代器模式git

一. 迭代器模式

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 {
        @Override
        public Iterator iterator() {
            return new ConcreteIterator();
        }
        private class ConcreteIterator implements Iterator {
            @Override
            public Object next() {
                System.out.println("ConcreteIterator next ...");
                return null;
            }
            @Override
            public 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.git

ENDgithub

相关文章
相关标签/搜索