Java
Usage examples: The pattern is very common in Java code. Many frameworks and libraries use it to provide a standard way for traversing their collections.
Here are some examples from core Java libraries:
All implementations of
java.util.Iterator(alsojava.util.Scanner).All implementations of
java.util.Enumeration.
Identification: Iterator is easy to recognize by the navigation methods (such as next, previous and others). Client code that uses iterators might not have direct access to the collection being traversed.
Iterating over social network profiles
In this example, the Iterator pattern is used to go over social profiles of a remote social network collection without exposing any of the communication details to the client code.
iterators
iterators/ProfileIterator.java: Defines profile interface
package refactoring_guru.iterator.example.iterators;
import refactoring_guru.iterator.example.profile.Profile;
public interface ProfileIterator {
boolean hasNext();
Profile getNext();
void reset();
}iterators/FacebookIterator.java: Implements iteration over Facebook profiles
iterators/LinkedInIterator.java: Implements iteration over LinkedIn profiles
social_networks
social_networks/SocialNetwork.java: Defines common social network interface
social_networks/Facebook.java: Facebook
social_networks/LinkedIn.java: LinkedIn
profile
profile/Profile.java: Social profiles
spammer
spammer/SocialSpammer.java: Message sending app
Demo.java: Client code
OutputDemo.txt: Execution result
Last updated