[Design Pattern] Verhaltensmuster: Iterator


Thomas Darimont

Premium-User
Hallo,

dieser Beitrag erklärt das Verhaltensmuster: Iterator
Java:
package de.tutorials.design.patterns.behavioral;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class IteratorExample {

	public static void main(String[] args) {
		List<String> list = Arrays.asList("A","B","C");
		demoExternalIterator(list);
		
		System.out.println("####");
		
		demoInternalIterator(list);
	}
	
	private static void demoExternalIterator(List<String> list) {
		Iterator<String> iterator = list.iterator();
		while(iterator.hasNext()){
			System.out.println(iterator.next());
		}
	}
	
	private static void demoInternalIterator(List<String> list) {
		ForEach<String> forEach = new ForEach<String>(list) {
			public void apply(String element) {
				System.out.println(element);
			}
		};
		
		forEach.loop();
	}

	
	static abstract class ForEach<E>{
		
		final Iterable<E> iterable;
		
		public ForEach(Iterable<E> iterable) {
			this.iterable = iterable;
		}

		public void loop(){
			Iterator<E> iterator = iterable.iterator();
			while(iterator.hasNext()){
				apply(iterator.next());
			}
		}
		
		public abstract void apply(E element);
	}

}
Ausgabe
Code:
A
B
C
####
A
B
C
Gruß Tom