java设计模式之迭代器模式

 

一、定义

提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。

二、代码实例

  1. 需求

    自己写一个iterator迭代器,遍历list。

  2. 代码实现

迭代器接口:

public interface Iterator {
    public Object first();

    public Object next();

    public boolean isDone();

    public Object currentItem();
}

具体迭代类型接口:

public interface Aggregate {
    public Iterator createIterator();
}

迭代器实现类:

public class ConcreteIterator implements Iterator {

    private ConcreteAggregate aggregate;

    private int current = 0;

    public ConcreteIterator(ConcreteAggregate aggregate) {
        this.aggregate = aggregate;
    }

    @Override
    public Object first() {
        return aggregate.get(0);
    }

    @Override
    public Object next() {
        Object result = null;
        current++;
        if (current < aggregate.count()) {
            result = aggregate.get(current);
        }
        return result;
    }

    @Override
    public boolean isDone() {
        return current >= aggregate.count() ? true : false;
    }

    @Override
    public Object currentItem() {
        return aggregate.get(current);
    }
}

list迭代器实现类:

public class ConcreteAggregate implements Aggregate {

    private List items = new ArrayList<>();

    @Override
    public Iterator createIterator() {
        return new ConcreteIterator(this);
    }

    public int count() {
        return items.size();
    }

    public Object get(int index) {
        return items.get(index);
    }
    public Object add(Object value) {
        return items.add(value);
    }

} 
  

测试类:

public class Test {
    public static void main(String[] args) {
        ConcreteAggregate aggregate = new ConcreteAggregate();
        aggregate.add("张三");
        aggregate.add("李四");
        aggregate.add("王五");
        aggregate.add("赵六");
        aggregate.add("田七");

        Iterator iterator = new ConcreteIterator(aggregate);
        while (!iterator.isDone()) {
            System.out.println(iterator.currentItem() + ",请买票");
            iterator.next();
        }

    }
}

 

你可能感兴趣的:(java,#设计模式,java,设计模式,迭代器模式)