Design Pattern Iterator - PowerPoint PPT Presentation

1 / 38
About This Presentation
Title:

Design Pattern Iterator

Description:

system should be independent of how products are created, composed and represented ... compose objects into tree structures to represent part-whole hierarchies. ... – PowerPoint PPT presentation

Number of Views:26
Avg rating:3.0/5.0
Slides: 39
Provided by: michael742
Category:

less

Transcript and Presenter's Notes

Title: Design Pattern Iterator


1
Design Pattern Iterator
  • aka Cursor
  • a behavioral pattern
  • intent
  • allow sequential access to elements of an
    aggregate without exposing underlying
    representation
  • motivation
  • want to be able to access elements of an
    aggregate object without exposing internal
    structure
  • want to use several different traversals
  • want different traversals pending on same list

2
Iterator - ModelGamma et al Design Patterns
elements of reusable object-oriented software,
p.259
Client
ConcreteIterator
return new ConcreteIterator(this)
3
  • use
  • access aggregate objects contents without
    exposing internal representation
  • support multiple traversals of aggregate objects
  • provide uniform interface for traversing
    different structures
  • model
  • consequences
  • supports variations in traversal of aggregate
  • simplified aggregate interface
  • more than one traversal can be pending on an
    aggregate
  • considerations
  • internal versus external iterators
  • who defines traversal algorithm

4
Iterators
  • based on Iterator Design Pattern
  • Iterator
  • public interface IteratorltEgt
  • public boolean hasNext()
  • public E next()
  • public void remove()
  • iterator() in Collection
  • sequential traversal
  • Enumeration
  • public interface EnumerationltEgt
  • public boolean hasMoreElements()
  • public E nextElement()
  • functionality of this interface is duplicated by
    the Iterator interface
  • new implementations should consider using
    Iterator in preference to Enumeration

5
Iterators (cont.)
  • ListIterator
  • public interface ListIteratorltEgt extends
    IteratorltEgt
  • public void add(E o)
  • public boolean hasPrevious()
  • public E previous()
  • public int nextIndex()
  • public int previousIndex()
  • public void set(E o)
  • listIterator() in List
  • forward and backward sequential traversal

6
Iterators (cont.)
  • iterating through Map views
  • views
  • key set
  • value collection
  • entry set (nested interface Map.Entry)
  • public static interface Map.EntryltK,Vgt
  • public K getKey()
  • public V getValue()
  • public V setValue(V v)

7
Design Pattern - Factory
  • a creational pattern
  • intent
  • To define an interface for creating objects but
    let subclasses decide which class to instantiate
    and how
  • motivation
  • Display classes for different sorting algorithms
  • SortDisplayFactory creates suitable instance
    depending on the algorithm actually used

8
Factory - Model
Product
Creates
ConcreteProduct
9
Design pattern - Abstract Factory
  • aka Kit
  • a creational pattern
  • intent
  • provide interface for creating families of
    related objects without specifying concrete
    representation
  • motivation
  • toolkit that supports multiple standards
  • e.g. look and feel of widgets
  • define WidgetFactory that declares interface for
    each kind of widget
  • concrete subclasses implement widgets for
    different look and feel standards
  • clients call operations in WidgetFactory,
    remaining independent of actual look and feel

10
Abstract Factory ModelGamma et al Design
Patterns elements of reusable object-oriented
software, p.88
Client
AbstractProductA
ProductA1
ProductA2
AbstractProductB
ProductB1
ProductB2
11
  • use
  • system should be independent of how products are
    created, composed and represented
  • family of products designed to be used together
  • want to provide library of products and reveal
    only interfaces not implementation
  • model
  • consequences
  • isolates concrete classes
  • easy to exchange product families
  • promotes consistency among products
  • difficult to support new kinds of products

12
Design pattern - Command
  • aka Action
  • a behavioral pattern
  • intent
  • To encapsulate an action as an object, so that
    actions can be passed as parameters, queued, and
    possible undone
  • Use the Command design pattern
  • when actions need to be passed as parameters.
  • when actions need to be queued and then executed
    later.
  • when actions can be undone.

13
Command - Structure
Invoker
Client
create
receiver
14
Command (cont.)
  • use
  • parameterize objects by actions to perform
  • specify, queue, and execute requests at different
    times
  • support undo
  • consequences
  • command are first-class objects
  • you can assemble commands into a composite
    command (design pattern composite)
  • easy to add new commands

15
Design pattern - Observer
  • aka Dependents, Publish-and-Subscribe
  • a behavioral pattern
  • intent
  • define dependencies between objects
  • when an object changes state, ensure all
    dependents are notified and updated
  • motivation
  • need to maintain consistency among cooperating
    classes
  • e.g. MVC GUI model
  • multiple views of same data
  • multiple windows on same text file
  • subject
  • observers

16
Model-View-Controller
Observers
a b c
change notification
requests, modifications
Subject
17
  • use
  • abstraction has two aspects, one dependent on the
    other
  • change to an object requires changing an unknown
    number of others
  • object needs to notify other objects without
    knowing details about them
  • consequences
  • abstract coupling between Subject and Observer
  • broadcast communication
  • unexpected updates
  • considerations
  • mapping subjects to observers
  • observing more than one subject
  • triggering the update
  • deleted subjects
  • self-consistent state in subject
  • how much information to send on update

18
Observer - Structure
observers
subject
19
Observer - Interaction
aConcreteSubject
anotherConcreteObserver
aConcreteObserver
SetState()
Notify()
Update()
GetState()
Update()
GetState()
20
Design Pattern Strategy
  • aka Policy
  • a behavioral pattern
  • intent
  • allow different variants of an algorithm
  • motivation
  • different traversals for sorted aggregates based
    on different orderings
  • it is difficult to add new orderings or vary
    existing once when they are an integral part of
    the traversal

21
Strategy - ModelGamma et al Design Patterns
elements of reusable object-oriented software,
p.315
22
  • use
  • many related classes differ only in their
    behavior. Strategies provide a way to configure a
    class with one of many behaviors.
  • you need different variants of an algorithm.
  • an algorithm uses data that clients shouldnt
    know about.
  • a class defines many behaviors, and these appear
    as multiple conditional statements in its
    operations.
  • model
  • consequences
  • hierarchies of strategies classes define a family
    of algorithms or behaviors for contexts to reuse.
  • an alternative to subclassing
  • eliminates conditional statements
  • choice of implementations
  • considerations
  • clients must be aware of different strategies
  • communication overhead between Strategy and
    Context
  • increased number of objects

23
Ordering and Sorting
  • order (partial order)
  • total order versus strictly partial order
  • natural order
  • by implementing Comparable interface
  • imposed order
  • by use of Comparator
  • Comparable
  • compareTo
  • parameter a.compareTo(b)
  • result
  • total order
  • consistency with equals

24
  • Comparator
  • public interface ComparatorltTgt
  • public int compare(T o1, T o2)
  • public boolean equals(Object obj)
  • Strategy Design Pattern
  • compare
  • parameters c.compare(a,b)
  • result
  • total order
  • consistency with equals

25
Design pattern - composite
  • Intent
  • compose objects into tree structures to represent
    part-whole hierarchies.
  • use the composite pattern when
  • you want to represent part-whole hierarchies of
    objects
  • you want clients to be able to ignore the
    difference between compositions of objects and
    individual objects

26
Composite - Structure
Client
children
Component
Operation() Add(c Component) Remove(c
Component) GetChildren() Collection
forall g in children g.Operation()
27
Example
  • public abstract class TreeltEgt implements
    IterableltEgt
  • private E element
  • public Tree(E element)
  • this.element element
  • public E getElement()
  • return element
  • public abstract boolean contains(E element)

28
Example (contd)
  • public boolean containsAll(CollectionltEgt
    collection)
  • boolean result true
  • for(E element collection)
  • result contains(element)
  • return result
  • public abstract int size()
  • public abstract int depth()
  • public IteratorltEgt iterator()
  • return new DfsTreeIteratorltEgt(this)

29
  • public class LeafltEgt extends TreeltEgt
  • public Leaf(E element)
  • super(element)
  • public boolean contains(E element)
  • return element.equals(getElement())
  • public int size()
  • return 1
  • public int depth()
  • return 1

30
  • public class NodeltEgt extends TreeltEgt
  • private TreeltEgt left
  • private TreeltEgt right
  • public Node(E element, TreeltEgt left, TreeltEgt
    right)
  • super(element)
  • this.left left
  • this.right right
  • public boolean contains(E element)
  • return element.equals(getElement())
    left.contains(element) right.contains(element)
  • public int size()
  • return left.size() right.size() 1

31
  • public int depth()
  • return Math.max(left.depth(),right.depth())
    1
  • public TreeltEgt getLeftSubTree()
  • return left
  • public TreeltEgt getRightSubTree()
  • return right

32
A tree
public static TreeltIntegergt createTree()
TreeltIntegergt t1 new LeafltIntegergt(8) Treelt
Integergt t2 new LeafltIntegergt(9) TreeltIntegergt
t3 new NodeltIntegergt(6,t1,t2) TreeltIntegergt
t4 new LeafltIntegergt(7) TreeltIntegergt t5
new NodeltIntegergt(3,t3,t4) TreeltIntegergt t6
new LeafltIntegergt(4) TreeltIntegergt t7 new
LeafltIntegergt(5) TreeltIntegergt t8 new
NodeltIntegergt(2,t6,t7) return new
NodeltIntegergt(1,t8,t5)
33
Iterators for Tree
  • public class DfsTreeIteratorltEgt implements
    IteratorltEgt
  • private IteratorltEgt iter
  • public DfsTreeIterator(TreeltEgt tree)
  • ListltEgt list new ArrayListltEgt()
  • toList(tree,list)
  • iter list.iterator()
  • public E next()
  • return iter.next()

34
  • public boolean hasNext()
  • return iter.hasNext()
  • public void remove()
  • throw new UnsupportedOperationException()
  • private void toList(TreeltEgt tree, ListltEgt list)
  • list.add(tree.getElement())
  • if (tree instanceof Nodelt?gt)
  • toList(((NodeltEgt) tree).getLeftSubTree(),li
    st)
  • toList(((NodeltEgt) tree).getRightSubTree(),l
    ist)

35
  • for(Integer n tree) System.out.print(n " ")
  • yields 1 2 4 5 3 6 8 9 7

36
  • public class BfsTreeIteratorltEgt implements
    IteratorltEgt
  • private IteratorltEgt iter
  • public BfsTreeIterator(TreeltEgt tree)
  • ListltEgt list new ArrayListltEgt()
  • LinkedListltTreeltEgtgt openList new
    LinkedListltTreeltEgtgt()
  • openList.add(tree)
  • toList(openList,list)
  • iter list.iterator()
  • public E next()
  • return iter.next()
  • public boolean hasNext()
  • return iter.hasNext()

37
  • public void remove()
  • throw new UnsupportedOperationException()
  • private void toList(LinkedListltTreeltEgtgt
    openList,
  • ListltEgt list)
  • while (!openList.isEmpty())
  • TreeltEgt tree openList.removeFirst()
  • list.add(tree.getElement())
  • if (tree instanceof Nodelt?gt)
  • openList.addLast(
  • ((NodeltEgt) tree).getLeftSubTree())
  • openList.addLast(
  • ((NodeltEgt) tree).getRightSubTree())

38
  • for(IteratorltIntegergt it new BfsTreeIteratorltInt
    egergt(tree)
  • it.hasNext() )
  • System.out.print(it.next() " ")
  • yields 1 2 3 4 5 6 7 8 9
Write a Comment
User Comments (0)
About PowerShow.com