时间: 2021-07-31 作者:daque
[手段] 供给一种本领程序考察一个会合东西中各个元素, 而又不需表露该东西的里面表白。 [何时运用?] 考察一个会合东西的实质而无需表露它的里面表白。扶助对会合东西的多种遍历。为遍历各别的会合构造供给一个一致的接口(即, 扶助多态迭代)。
[怎样运用?] java作风的示例步调:
//笼统的汇合 public interface aggregate {
public abstract iterator iterator();}
//笼统的iterator public interface iterator {
public abstract boolean hasnext(); public abstract object next();}
//简直的汇合 public class concreteaggregate implements aggregate {
private object[] collection; private int last = 0; public concreteaggregate() {
collection = new object[3];}
public object getitemat(int index) {
return collection[index];}
public void appenditem(object item) {
this.collection[last] = item; last++;}
public int getlength() {
return last;}
public iterator iterator() {
//爆发符合本人的iterator return new concreteiterator(this);}}
//简直的iterator public class concreteiterator implements iterator {
private concreteaggregate namecollection; //由它确定遍历的汇合典型 private int index; public concreteiterator(concreteaggregate collection) {
this.namecollection = collection; this.index = 0; }
public boolean hasnext() {
if (index < namecollection.getlength()) {
return true;} else {
return false;} } public object next() {
//经过一致的getitemat()接话柄现对各别典型汇合的遍历 object item = namecollection.getitemat(index); index++; return item;}}
public class iteratorexample { public static void main(string[] args) { concreteaggregate collection = new concreteaggregate(); collection.appenditem(new person("davis")); collection.appenditem(new person("frank")); collection.appenditem(new person("jeny"));
//it的简直典型依附于collection的典型而运用者并不须要关怀这内里的辨别
iterator it = collection.iterator(); //归来符合collection的iterator while (it.hasnext()) { person person = (person)it.next(); system.out.println("" + person.getname());}}}
如许遍历代码维持了一致的作风,进而使运用者不用关怀遍历的东西究竟是什么典型。