Iterator Pattern

2,513 views
2,443 views

Published on

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,513
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
92
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Iterator Pattern

  1. 1. Iterator  Design  Pa.ern   Stewart  Gleadow   University  of  Melbourne  
  2. 2. Intent   •  “Provide  a  way  to  access  the  elements  of  an   aggregate  object  sequen>ally  without   exposing  its  underlying  representa>on”                  –  GoF  
  3. 3. Mo3va3on   •  Hide  implementa3on  details   •  Allow  for  different  traversals   •  Separate  traversal  code  from  the  list  itself  
  4. 4. Basic  Structure   List Iterator count() first() add(Item) next() remove(Item) isDone() Item get(int index) Item currentItem() •  Provide  List  to  Iterator  (3ghtly  coupled)   •  Iterator  keeps  a  Cursor  to  current  loca3on  
  5. 5. Structure   Aggregate Iterator createIterator() first() next() isDone() Item currentItem() ConcreteAggregate ConcreteIterator createIterator() return new ConcreteIterator(this)
  6. 6. Types  of  Iterators   •  External:  client  controls  the  itera3on   •  Internal:  iterator  controls  itera3on   •  anonymous  func3ons   •  closures  /  blocks  
  7. 7. Applicability   •  List  processing  &  selec3on   •  Tree  traversals.  eg.  depth  first   •  Syntax  trees  -­‐>  Interpreter?  
  8. 8. Concurrency   •  hasNext()  or  !isDone()  implies  subsequent  call   to  currentItem()  will  pass   •  Iterators  get  a  copy  of  the  data?   •  Iterators  keep  track  of  modifica3ons?  
  9. 9. External  (Java)   Iterator<MyType> iter = list.iterator();! while(iter.hasNext())! !System.out.println(iter.next());! // OR! for(MyType item : list)! !System.out.println(item);!
  10. 10. External  (Ruby)   for item in list! !puts item! end! // OR! list.each { |item| puts item }!
  11. 11. Internal  (Java)   public abstract class Internal<T> {! !private Iterator<T> iter;! public void traverse() {! for(T item : iter)! process(item);! }! protected abstract process(T item);! }!
  12. 12. Internal  (Java)   Iterator<T> iter = list.iterator();! Internal<T> internal = new Internal<T>(iter)! {! !protected void process(T item) {! ! ! !if(condition)! ! ! ! !System.out.println(item);! !}! };!
  13. 13. Internal  (Ruby)   list.each { |item| puts item if condition }!

×