preface

The iterator pattern is also known as the cursor pattern. In most programming languages, iterators have become a basic class library that is used directly to traverse collection objects. The key idea is to separate access and traversal responsibilities from collection objects and put them into standard protocol objects.

directory

A, definitions,

It provides a way to access the elements of a container object without exposing the inner details of the object.

Two, mode principle analysis

Template code

Public interface Iterator{public Object next(); public Object next(); Public Boolean hasNext(); Public Boolean remove(); } public class ConcreteIterator implements Iterator{private Vector Vector = new Vector();} Public class ConcreteIterator implements Iterator{private Vector Vector = new Vector(); Public int cursor = 0; public ConcreteIterator(Vector _vector){ this.vector = _vector; Public Boolean hasNext(){if(this.cursor == this.vector-size ()){return false;} public Boolean hasNext(){if(this.cursor == this.vector-size ()){return false; }else{ return true; Public Object next(){Object result = null; if(this.hasNext()){ result = this.vector.get(this.cursor++); }else{ result = null; } return result; Public Boolean remove(){this.vector-remove (this.cursor); return true; Public void add(Object Object); public void add(Object Object); public void add(Object Object); Public void remove(Object Object); Public Iterator Iterator (); } public class ConcreteAggregate implements Aggregate{private Vector Vector = new Vector();} Public class ConcreteAggregate implements Aggregate{private Vector Vector = new Vector(); Public void add(Object Object){this.vector-add (Object); } public ConcreteIterator Iterator(){return new ConcreteIterator(this.vector); } public void remove(Object Object){this.vector-remvoe (Object); }} public class Client{public static void main(String[] args){// Aggregate agg = new ConcreteAggregate(); // Add data agg.add(" ABC "); agg.add("aaa"); agg.add("1234"); Iterator = agg. Iterator (); while(iterator.hasNext()){ System.out.println(iterator.next()); }}}Copy the code

Iii. Usage Scenarios

  • Hides the complexity of the traversal algorithm from the client

  • When repeated loop traversal logic needs to be simplified

Four advantages,

  • To meet the single responsibility principle, the traversal algorithm code is uniformly extracted and encapsulated into independent classes, whose responsibility is only to traverse the data

  • To satisfy the open closed principle, when a new set of objects needs to be extended, it only needs to add concrete object iterators and concrete collection classes

  • Avoids the repetitive code problem of using for loops directly

Five, the disadvantages

  • Increased the number of subclasses

  • Increased system complexity