版权声明:本文为博主原创文章,未经博主允许不得转载。个人公众号:百草疯茂 https://blog.csdn.net/wang_pengyu/article/details/84891987
package com.test.DPs.XingWei.Iterator;
/**
* 行为型:Iterator-迭代器 外观:作用面为 对象
*
* 用途:提供一种方法顺序访问一个聚合对象中各个元素,而又不需要暴露该对象的内部表示。
* 理解:一是需要遍历的对象,即聚集对象,
* 二是迭代器对象,用于对聚集对象进行遍历访问
*/
interface Collection{
Iterator iterator();
Object get(int i);
int size();
}
interface Iterator{
Object previous();
Object next();
boolean hasNext();
Object first();
}
class myCollection implements Collection{
public String string[] = {"A","B","C","D","E"};
@Override
public Iterator iterator(){
return new myIterator(this);
}
@Override
public Object get(int i) {
return string[i];
}
@Override
public int size() {
return string.length;
}
}
class myIterator implements Iterator{
private Collection collection;
private int pos = 1;
public myIterator(Collection collection){
this.collection = collection;
}
@Override
public Object previous(){
if(pos>0){
pos--;
}
return collection.get(pos);
}
@Override
public Object next() {
if(pos<collection.size()-1){
pos++;
}
return collection.get(pos);
}
@Override
public boolean hasNext() {
if(pos<collection.size()-1){
return true;
}else{
return false;
}
}
@Override
public Object first() {
pos = 0;
return collection.get(pos);
}
}