Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Iterator Pattern

2,757 views

Published on

  • Be the first to comment

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 }!

×