做资源下载网站好吗,婚恋网站建设公司排名,专业建设的几个方面,迪拜哪个网站是做网站的迭代器模式提供一种方法访问一个容器对象中各个元素#xff0c;而又不需暴露该对象的内部细节。 设计模式#xff0c;一定要敲代码理解
抽象迭代器
/*** 迭代抽象* */
public interface IteratorA {A next();boolean hasNext();
}迭代器实现
/*** author ggbond*…迭代器模式提供一种方法访问一个容器对象中各个元素而又不需暴露该对象的内部细节。 设计模式一定要敲代码理解
抽象迭代器
/*** 迭代抽象* */
public interface IteratorA {A next();boolean hasNext();
}迭代器实现
/*** author ggbond* date 2024年04月13日 09:08*/
public class MyIteratorT implements IteratorT{private MyCollectionT myCollection;private int size;private int index; //索引游标public MyIterator(MyCollectionT myCollection) {this.myCollection myCollection;this.index 0;this.size myCollection.getSize();}Overridepublic T next() {if (index size) {return myCollection.getNext(index);}return null;}Overridepublic boolean hasNext() {return index size;}
}抽象集合
/*** 定义集合* */
public interface CollectionA {boolean add(A a);boolean remove(A a);IteratorA createIterator();}集合实现
/*** author ggbond* date 2024年04月13日 09:12*/
public class MyCollectionT implements CollectionT{private ArrayListT listnew ArrayListT();public int getSize() {return list.size();}Overridepublic boolean add(T t) {return list.add(t);}Overridepublic boolean remove(T t) {return list.remove(t);}Overridepublic Iterator createIterator() {return new MyIterator(this);}public T getNext(int i) {return list.get(i);}
}迭代对象
/*** author ggbond* date 2024年04月13日 09:29*/
public class Person {String name;String cardID;public Person(String name, String cardID) {this.name name;this.cardID cardID;}public String getName() {return name;}public void setName(String name) {this.name name;}public String getCardID() {return cardID;}public void setCardID(String cardID) {this.cardID cardID;}Overridepublic String toString() {return Person{ name name \ , cardID cardID \ };}
}测试与结果
public class Main {public static void main(String[] args) {Person p1 new Person(ggbond1,001);Person p2 new Person(ggbond2,002);Person p3 new Person(ggbond3,003);Person p4 new Person(ggbond4,004);CollectionPerson collectionnew MyCollection();collection.add(p1);collection.add(p2);collection.add(p3);collection.add(p4);IteratorPerson iterator collection.createIterator();while (iterator.hasNext()) {System.out.println(iterator.next());}}
}Person{nameggbond1, cardID001}
Person{nameggbond2, cardID002}
Person{nameggbond3, cardID003}
Person{nameggbond4, cardID004}总结
迭代器模式将数据存储和数据遍历的职责进行分离。但针对不同结构的迭代对象迭代方式需进行添加。
代码下载
代码下载