Design Patterns Iterator

Iterative mode 

defined Iterator (the Iterator) mode :
  providing a polymeric object to a series of sequential access data objects, without exposing the internal representation of the aggregate object.
  Iterator is an object behavioral patterns,

  is inserted between a client access iterator class type polymerization, which separates the aggregate object and its traversal behavior, the customer also hides its internal details

Abstract polymerization (Aggregate) Roles:
  defined storage, add, delete, and create interfaces aggregate objects iterator object.
Specific polymerization (ConcreteAggregate) role:
  to achieve polymerization abstract class returns an iterator specific examples.
Abstract iterator (the Iterator) Role:
  defining access interface elements and traverse the polymerization, generally comprising hasNext (), first (), next () method and the like.
DETAILED iterator (Concretelterator) Role:
  implement the abstract methods defined in an interface Iterator complete traversal of the aggregate object, recording the current position of the traverse.
 1 public class Iterator {
 2     public static void main(String[] args) {
 3         ConcreteAggregate a = new ConcreteAggregate();
 4         a.add(1);
 5         a.add("小花");
 6         a.add(1.1);
 7         a.remove(1);
 8         Iteratoring iterator = a.getIterator();
 9         while (iterator.hasNext()) {
10             System.out.println(iterator.next());
11         }
12     }
13 }
14 
15 // 抽象迭代器
16 interface Iteratoring {
17     public boolean hasNext();
18 
19     public Object next();
20 }
21 
22 //具体迭代器
23 class Concretelterator implements Iteratoring {
24 
25     private ArrayList<Object> li;
26 
27     public Concretelterator(ArrayList<Object> li) {
28         this.li = li;
29     }
30 
31     int count = 0;
32 
33     @Override
34     public boolean hasNext() {
35         if (count < li.size()) {
36             return true;
37         }
38         return false;
39     }
40 
41     @Override
42     public Object next() {
43         if (hasNext()) {
44             return li.get(count++);
45         }
46         return null;
47     }
48 }
49 
50 //抽象聚合
51 interface Aggregate {
52     public void add(Object obj);
53 
54     public void remove(Object obj);
55 
56     public Iteratoring getIterator();
57 }
58 
59 //具体聚合
60 class ConcreteAggregate implements Aggregate {
61 
62     private ArrayList arr = new ArrayList();
63 
64     @Override
65     public void add(Object obj) {
66         arr.add(obj);
67     }
68 
69     @Override
70     public void remove(Object obj) {
71         arr.remove(obj);
72     }
73 
74     @Override
75     public Iteratoring getIterator() {
76         return new Concretelterator(arr);
77     }
78 }

Guess you like

Origin www.cnblogs.com/loveer/p/11279526.html