This is the 27th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Author’s other platforms:

| CSDN:blog.csdn.net/qq\_4115394…

| the nuggets: juejin. Cn/user / 651387…

| zhihu: www.zhihu.com/people/1024…

| GitHub:github.com/JiangXia-10…

| public no. : 1024 notes

This article is about 2,068 words and will take about 8 minutes to read

define

The Iterator Pattern primarily provides a way to access elements of a container object without exposing the inner details of the object. The iterator pattern is an object behavior pattern.

Iterators are often used in Java’s collection processing. A collection is a container that can contain objects, such as List, Set, Map, and can be used to iterate through the objects in the container one by one. Such as:

Public class IteratorTest {public static void main(String[] args) {ArrayList<String> Sites = new ArrayList<String>(); Sites. The add (" zhang fei "); Sites. The add (" liu "); Sites. The add (" guan yu "); Zhaoyun sites. The add (" "); Iterator<String> it = site.iterator (); System.out.println(it.next())); }}Copy the code

The results are as follows:

Part of the

There are four main parts to implementing an iterator pattern:

1. Aggregate: Defines the interface for storing, adding, deleting Aggregate objects and creating iterator objects. It provides an iterator() method, such as the Java Collection interface, List interface, Set interface, etc.

2, Concrete Aggregate: Implement abstract container class, return a Concrete iterator instance, such as List interface ordered List implementation ArrayList, List interface linked List implementation LinkList, Set interface hash List implementation HashSet, etc.

Abstract iterators: Abstract iterators are interfaces that define access to and traversal over aggregate elements. They typically contain three methods: first() to get the first element, next() to get the next element, and hasNext() to determine if there is a next element.

Concretelterator: Implements methods defined in the abstract iterator interface, iterates through collections, and records the current location of the iterator.

example

Following is a concrete example of implementing an iterator pattern:

Start by defining an interface for an abstract container:

/** * public interface Aggregate {public void add(Object obj); public void remove(Object obj); public Iterator iterator(); }Copy the code

Define a concrete container class that implements the abstract container interface and implements the interface methods:

public class ConcreteAggregate implements Aggregate{ private List list = new ArrayList(); @Override public void add(Object obj) { list.add(obj); } @Override public void remove(Object obj) { list.remove(obj); } @Override public Iterator iterator() { return new ConcreteIterator(list); }}Copy the code

Iterator interface:

public interface Iterator {
    public Object next();
    public boolean hasNext();
}
Copy the code

Concrete iterator classes implement the iterator interface:

public class ConcreteIterator implements Iterator { public List list = new ArrayList(); public int index = 0; public ConcreteIterator(List list) { this.list = list; } @Override public Object next() { Object obj = null; if(this.hasNext()){ obj = this.list.get(index++); } return obj; } @Override public boolean hasNext() { if(index==list.size()){ return false; } return true; }}Copy the code

The test class:

public class IteratorPatternTest { public static void main(String[] args) { Aggregate aggregate = new ConcreteAggregate(); Aggregate. The add (" liu "); Aggregate. The add (" guan yu "); Aggregate. The add (" zhang fei "); Iterator it = aggregate.iterator(); while(it.hasNext()){ String str = (String)it.next(); System.out.println(str); }}}Copy the code

Running results:

Advantages of the iterator pattern

1. Access the contents of a collection without exposing its internal representation, and the task of traversing is left to iterators, simplifying the collection class;

2. Good encapsulation, providing a unified interface for traversing different aggregation structures, and users only need to get iterators to traverse, and do not need to care about the traversal algorithm;

Disadvantages of the iterator pattern

1. If convenient and simple collections, such as arrays or lists, are needed, it is difficult to use iterators. Therefore, it is necessary to choose appropriate scenes to use iterators.

2. Iterator mode changes the collection structure of iterators while iterating will cause exceptions;

Application scenarios

The iterator pattern applies to the following situations:

The iterator pattern can be used if you need to access the contents of a collection object without exposing its internal details.

Iterator patterns can also be used if you need to iterate over different collection structures and provide a unified interface for them.

3. Iterators and containers are closely related, and many languages provide iterators when implementing containers, so we can generally use the iterator pattern provided by the language, and do not need to practice the iterator pattern.

conclusion

The iterator pattern primarily provides a way to access the elements of a container object without exposing the inner details of the object. However, many languages provide iterators when implementing containers, so we can generally use the iterator pattern provided by the language. We do not need to deliberately implement the iterator pattern.

Finally, this article and all of the previous design pattern sample code will be synchronized to Github, if you need to download star.

Making address:

Github.com/JiangXia-10…

Related recommendations:

Learning Design Patterns from Scratch part 1: What are Design Patterns

Learning design Patterns from scratch (PART 2) : Singleton patterns

Learning design Patterns from Scratch (3)

Learning design Patterns from Scratch (4) : Factory Pattern

Learning Design Pattern from Scratch (5) : Builder Pattern

Learning design Patterns from Scratch (6) : Adapter Pattern

Learn design Pattern from scratch (6) : Proxy Pattern

Decorator Pattern ()

Learning design Patterns from Scratch (9) : Facade Pattern

Learning design Patterns from Scratch (10) : Bridge Pattern

Learning Design Patterns from Scratch (11) : Composite Pattern

Learn design Pattern from scratch (12) : Flyweight Pattern

Learning Design Patterns from Scratch (13) : Visitor Pattern

Learning Design Pattern from Scratch (14) : Mediator Pattern

Learning design Patterns from Scratch (15) : Template Method Pattern

Learning Design Patterns from Scratch (16) : Strategy Pattern

Learning design Patterns from Scratch (17)

Learning Design Patterns from Scratch (18) : State Pattern

Learning design Patterns from Scratch (19) : Chain of Responsibility Pattern