Presentation is loading. Please wait.

Presentation is loading. Please wait.

Part 1: Composition, Aggregation, and Delegation Part 2: Iterator COMP 401 Fall 2014 Lecture 10 9/18/2014.

Similar presentations


Presentation on theme: "Part 1: Composition, Aggregation, and Delegation Part 2: Iterator COMP 401 Fall 2014 Lecture 10 9/18/2014."— Presentation transcript:

1 Part 1: Composition, Aggregation, and Delegation Part 2: Iterator COMP 401 Fall 2014 Lecture 10 9/18/2014

2 Layers of Abstraction Simple objects – Object state (i.e., fields) are basic data types As objects become more complex… – Encapsulated object state is complex enough to require additional “layers of abstraction”. – Object state is modeled by a combination of other objects. – Recall early examples with Triangle and Point Lecture 5, ta.v09 and ta.v10

3 Composition and Aggregation Two design techniques for creating an object that encapsulates other objects. – Whole / part relationship – Any specific situation is not necessarily strictly one or the other. In a nutshull… – Composition The individual parts that make up the whole are “owned” solely by the whole. – They don’t otherwise have a reason for being. – Aggregation The individual parts that make up the whole may also exist on their own outside of the whole. – Or even as a part of other objects.

4 Example of Aggregation lec10.ex1 – Course Models a course at the university Encapsulates Room, Professor, and a list of Student objects

5 Characteristics of Aggregation Encapsulated objects provided externally – As parameters to constructor – Getters and setters for these components often provided. Encapsulated objects may be independently referenced outside of the aggregating object – Including possibly as part of another aggregation.

6 Example of Composition lec10.ex2 – Car Two implementations: HondaOdyssey and Porche911 Both encapsulate an implementation of Horn and an implementation of Engine – Implementations of Engine written with inheritance. EngineImpl provides most of the implementation – Abstract class ManualEngine and AutomaticEngine are subclasses – Override setGear()

7 Characteristics of Composition Encapsulated objects created internally – Usually within the constructor – No setters and often no getters Encapsulated objects do not make sense outside of the abstraction. – Not shared with other abstractions Functionality / state of encapsulated objects only accessible through the abstraction

8 Delegation Claiming an “is-a” relationship with an interface but relying on another object to actually do the work. Can occur with either aggregation or composition. – Although more common with composition Composition example revisited – lec10.ex3 – Both Car implementations also now claim Horn and/or AdjustableHorn interfaces as well. Actual work of these interfaces delegated to internal horn object.

9 Part 2: Iterator

10 Design Situation Suppose we have an object that encapsulates some sort of collection. – SongLibrary A collection of songs in an iTunes-like system – PolygonModel A collection of polygons in a 3D modeling system

11 Design Situation Now suppose we have code outside of this collection object that needs to examine each element of the underlying collection in turn. – SongFilter A object that represents a search criteria to be applied to a collection of songs – An intersection test in which each polygon of a PolygonModel needs to be evaluated

12 Strategy 1: Provide access to underlying collection as an array. SongLibrary – public Song[] getSongs() PolygonModel – public Polygon[] getPolygons() Drawbacks? – May have to do a lot of work to create the array – Collection may be result of generative process There may be no “end” to the collection. Or the collection may be large so we don’t want to provide the whole thing at once.

13 Strategy 2: Provide index access to each underlying item in collection SongLibrary – public int getNumSongs(); – public Song getSong(int song_idx); PolygonModel – public int getNumPolygons(); – public Polygon getPolygon(int polygon_idx); Drawbacks? – Doesn’t help with generative collections – Imposes restrictions on how collection is represented and linearized – Deteriorates encapsulation

14 Strategy 3: Internalize a “cursor” SongLibrary – public void resetSongCursor(); – public Song getNextSong(); – public boolean isCursorAtEnd(); Drawbacks? – Can’t have two traversals going at the same time. – But, this does come close.

15 Iterator Design Pattern “Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation” – Gang of Four, Design Patterns Consider: for(int i=0; i<slist.size(); i++) { Song next_song = slist.get(i); // Do something with next_song. }

16 Iterator Design Pattern Iterator object encapsulates details of item traversal. – Understands details of the underlying collection. – Manages order of items May want a traversal that is not just first to last. Underlying collection may not have a natural linear order. – Manages state of traversal Allows traversal to be picked up again later. Assumption: underlying collection is not changed or modified while the traversal is occurring. – Iterator should be able to detect this and signal an error – Variant of pattern will have iterator provide methods that modify underlying collection safely

17 Components of Iterator Pattern Collection object is “iterable” – Provides a method that returns an object that acts as an iterator. Iterator object provides access to the elements in turn. – At the very least: A method to test whether more items exist. A method to retrieve the next item. – Other possible features: Methods that remove an item safely. Method to “peek” at the next item. Method to reset the traversal.

18 Java Iterator Pattern Interfaces The Java Collections Framework defines two generic interfaces for supporting the iterable design pattern – Implemented by the various collection types such as List, Map, Set, etc. Iterable – Interator iterator() Iterator

19 boolean hasNext() – Are we at the end of the traversal? E next() – Get the next item of the traversal. – Throws a runtime exception if no next item. void remove() – Not supported by all implementations. – Safely removes last item retrieved by next() from the underlying collection.

20 Iterable examples lec10.ex4 – Main1 Simple use – Main2 Parallel iterators – Main3 Simultaneous iterators – Main4 for – each syntactic sugar

21 Main1 Visualized (1) ArrayList<Song> slistArrayList<Song> slist 0 Words and Guitar Dig Me Out Jenny Little Babies Buy Her Candy 1 2 3 4

22 Main1 Visualized (2) ArrayList<Song> slistArrayList<Song> slist 0 Words and Guitar Dig Me Out Jenny Little Babies Buy Her Candy 1 2 3 4 Iterator iter 0 0 next_idx list

23 Main1 Visualized (3) ArrayList<Song> slistArrayList<Song> slist 0 Words and Guitar Dig Me Out Jenny Little Babies Buy Her Candy 1 2 3 4 Iterator iter 0 0 next_idx list public boolean hasNext() { if (next_idx < list.size()) { return true; } return false; } NOTE: This may or may not be how it is actually implemented, but it is effectively what is going on.

24 Main1 Visualized (4) ArrayList<Song> slistArrayList<Song> slist 0 Words and Guitar Dig Me Out Jenny Little Babies Buy Her Candy 1 2 3 4 Iterator iter 1 1 next_idx list public Song next() { Song s = list.get(next_idx); next_idx++; return s; } NOTE: Real implementation would first check to see if hasNext() is still true and throw an exception otherwise.

25 lec10.ex4.Main2 Parallel iteration – Processes two different lists Iterator associated with each. Iterators advance unevenly

26 lec10.ex4.Main3 Simultaneous iteration – 2 Iterators, 1 List Insert your own joke here.

27 for - each Java provides “syntactic sugar” for a particularly common use of iterators. – for-each loop – Supposing e_coll is Iterable, then these are equivalent: Iterator iter = e_coll.iterator(); while (iter.hasNext()) { E elem = iter.next(); // Do something with element } for (E elem : e_coll) { // Do something with elem } lec10.ex4.Main4

28 for-each with Array The for-each construct also works with Arrays Useful if you need to process the elements of an array but do not need the index. String[] names = new String[] {“Amy”, “Mike”, “Cameron”, “Claire”}; for (String n : names) { System.out.println(n); }

29 lec10.ex5 A more complicated iterator – Can build iterators that do things other than just go through every item. Prior examples made use of Iterator built into List, here we are going to implement our own specialized version of Iterator


Download ppt "Part 1: Composition, Aggregation, and Delegation Part 2: Iterator COMP 401 Fall 2014 Lecture 10 9/18/2014."

Similar presentations


Ads by Google