2、迭代器模式(Iterator)

2020-07-17  本文已影响0人  火山_6c7b

1. 迭代器模式

1.1 迭代器模式简介

  遍历一个聚合对象,又不需要了解聚合对象的内部结构,可以使用迭代器模式。

特点:

1.2 迭代器模式组成

UML图:

迭代器模式uml.png

主要角色:

2. 迭代器实现示例

Iterator:

public interface Iterator {
    public abstract boolean hasNext();
    public abstract Object next();
}

Aggregate:

public interface Aggregate {
    public abstract Iterator iterator();
}

Television:

public class Television implements Aggregate {

    private Channel[] channels;
    private int last = 0;

    public Television(int maxsize) {
        this.channels = new Channel[maxsize];
    }

    public Channel getChannelAt(int index) {
        return Channels[index];
    }

    public void appendChannel(Channel Channel) {
        this.Channels[last] = Channel;
        last++;
    }

    public int getLength(){
        return last;
    }

    @Override
    public Iterator iterator() {
        return new ChannelIterator(this);
    }
}

ChannelIterator:

public class TelevisionIterator implements Iterator {

    private Television television;
    private int index;

    public TelevisionIterator(Television television) {
        this.Television = television;
        this.index = 0;
    }

    @Override
    public boolean hasNext() {
        if (index < television.getLength()) {
            return true;
        }
        return false;
    }

    @Override
    public Object next() {
        Channel channel = television.getChannelAt(index);
        index ++;
        return channel;
    }
}

使用示例:

Television television = new Television(4);
television.appendChannel(new Channel("cctv-1"));
television.appendChannel(new Channel("cctv-4"));
television.appendChannel(new Channel("cctv-6"));
television.appendChannel(new Channel("cctv-8"));
Iterator it = television.iterator();
while (it.hasNext()) {
    Channel channel = (Channel) it.next();
    System.out.println(channel.getName());
}
上一篇下一篇

猜你喜欢

热点阅读