Design pattern fourteen, iterator pattern

The iterator mode provides a unified interface for traversing the collection elements, using a consistent method to traverse the collection elements, without knowing the underlying representation of the collection object, that is: not exposing its internal structure

The role of
the type of hidden
inner class can access unlimited external members of its class, including private members

/*
*Inner class (inner class)
*Definition: the class defined in the class, method body, interface
*Function
*Used for type hiding
*Inner class has unlimited access to the members of its outer class, including private members
*/

/*Iterator mode (iterator): abstraction of access actions

  • A collection of data stored at the bottom: an array (int), private, not directly accessible by the outside world
  • Implement iterators through private inner classes
  • Named inner class
  • Anonymous inner class
    */
//迭代器接口
public interface Iterator {
    
    
	int current();
	int next();
	boolean isFinish();
}


public class Sequence {
    
    
	private int[] data;
	private int cur;
	
	public Sequence(int n) {
    
    
		data = new int[n];
		for (int k = 1; k <= n; k++) data[k-1] = k;
	}
	
	//返回一个接口,让外界按指定的顺序读取data
	public Iterator iterator() {
    
    
		cur = 0;
		return new NormalIterator();
	}
	
    	//顺序访问,类型隐藏,DAO
	private class NormalIterator implements Iterator {
    
    
		@Override
		public int current() {
    
    
			return data[cur];
		}
		@Override
		public int next() {
    
    
			if (cur < data.length) cur++;
			if (isFinish()) return -1;
			return data[cur];
		}
		@Override
		public boolean isFinish() {
    
    
			return (cur == data.length);
		}
	}
	
	//逆序访问,在方法中定义的匿名内部类
	public Iterator invIterator() {
    
    
		cur = data.length - 1;
		//改为用在方法中定义的匿名内部类实现
		return new Iterator() {
    
    
			@Override
			public int current() {
    
    
				return data[cur];
			}
			@Override
			public int next() {
    
    
				if (cur >=0) cur--;
				if (isFinish()) return -1;
				return data[cur];
			}
			@Override
			public boolean isFinish() {
    
    
				return (cur == -1);
			}
		};
	}

    
}

public static void main(String[] args) {
    
    
		Sequence s = new Sequence(20);
		//Iterator iter = s.iterator();
		
		Iterator iter = s.invIterator();
		
		do {
    
    
			System.out.print(iter.current() + " ");
			iter.next();
		} while (!iter.isFinish());
}

Guess you like

Origin blog.csdn.net/weixin_45401129/article/details/114629486