커서 모드라고도하는 반복자 모드. GOF가 제공 한 정의는 객체의 내부 세부 사항을 노출시키지 않고 컨테이너 객체의 다양한 요소에 액세스하는 방법을 제공하는 것입니다.
반복자 패턴은 다음과 같은 역할로 구성됩니다.
반복자 역할 : 반복자 역할은 액세스 및 트래버스 요소에 대한 인터페이스를 정의하는 역할을 담당합니다.
콘크리트 반복자 역할 : 특정 반복자 역할은 반복자 인터페이스를 구현하고 트래버스에서 현재 위치를 기록해야합니다.
컨테이너 : 컨테이너 역할은 특정 반복 역할을 만들기위한 인터페이스를 제공하는 역할을 담당합니다.
콘크리트 컨테이너 : 특정 컨테이너 역할은 인터페이스를 구현하여 특정 반복 역할을 생성합니다. 이 특정 반복 역할은 컨테이너의 구조와 관련이 있습니다.
Java 구현 예
클래스 다이어그램 :
암호:
/ ** * 데이터 저장에 대한 java.util.collection과 유사한 사용자 정의 컬렉션 인터페이스 * @author stone */ public interface icollection <t> {iiterator <t> iterator (); // 반복자 void add (t t)를 반환합니다. t get (int index); } / ** * Custom Ierator 인터페이스는 java.util.iterator와 유사합니다. * 컬렉션 클래스 iCollection * @author Stone */ public interface iiterator <t> {boolean hasnext (); 부울 hasprevious (); t 다음 (); t 이전 (); } / ** * 컬렉션 클래스, myiterator * @author stone */ public class mycollection <t> Icollection <t> {private t [] arys; 개인 int index = -1; 개인 int 용량 = 5; public myCollection () {this.arys = (t []) 새 개체 [용량]; } @override public iiterator <t> iterator () {return new myiterator <t> (this); } @override public void add (t t) {index ++; if (index == 용량) {용량 *= 2; this.arys = arrays.copyof (arys, capare); } this.arys [index] = t; } @override public t get (int index) {return this.arys [index]; }} /** 새로운 스토리지 구조가있는 경우, 새로운 iiTerator에 해당하는 새로운 iCollection ({ "rawtypes", "unchecked"}) 공개 클래스 테스트 {public static void main (string [] args) {icolection <integer collection = new mycollection> (); 추가 (수집, 3, 5, 8, 12, 3, 3, 5); for (iiterator <integer> iterator = collection.iterator (); iterator.hasnext ();) {system.out.println (iterator.next ()); } system.out.println ( "------------------------------------------ iCollection Collection2 = New MyCollection (); add (collection2, "a", "b", "c", 3, 8, 12, 3, 5); for (iiterator iterator = collection2.terator (); iterator.hasnext ();) {system.out.println (iterator.next ()); }} static <t> void add (icollection <t> c, t ... a) {for (t i : a) {c.add (i); }}}}인쇄:
3 5 8 12 3 3 5 ------------------ ABC 3 8 12 3 5