Frameworks • Concepts – set of cooperating classes Frameworks – extending some class – inversion of control • Examples from java API Horstmann ch.8-8.4 – swing, applet, collection • Constructing a framework – graph editor Frameworks Applets • Set of cooperating classes • Applet: Java program • Structures the essential mechanisms of a problem that runs in a web domain browser • Example: Swing is a GUI framework • Programmer forms • Framework != design pattern subclass of Applet • Typical framework uses multiple design patterns or JApplet Application Frameworks • Overwrites • Implements services common to a type of applications init / destroy • Programmer forms subclasses of framework classes start / stop • Result is an application paint • Inversion of control: framework controls execution flow Applets Example Applet • Interacts with ambient browser • Shows scrolling banner getParameter • init reads parameters showDocument • start / stop start and stop timer • HTML page contains applet tag and parameters • paint paints the applet surface <applet code="BannerApplet.class" width="300" height="100"> <param name="message" value="Hello, World!"/> <param name="fontname" value="Serif"/> <param name="fontsize" value="64"/> <param name="delay" value="10"/> </applet> • Run by UNIX command: appletviewer BannerApplet.html
Example Applet Applets as a Framework public class BannerApplet extends Applet { public void init () { get parameters: message, fontname, fontsize, delay get bounds; set font; • Applet programmer uses inheritance timer = new Timer(delay, new ActionListener() { • Applet class deals with generic behavior public void actionPerformed(ActionEvent event) { start--; (browser interaction) if (start + bounds.getWidth() < 0) start=getWidth(); • Inversion of control: applet calls init , repaint(); start , stop , destroy }}); } public void start () { timer.start(); } public void stop () { timer.stop(); } public void paint (Graphics g) { g.setFont(font); g.drawString(message, start, (int)-bounds.getY()); } private instance variables } Collections Framework: Collections Framework Interface Types • Collection : the most general collection • Java library supplies standard data structures interface type • Supplies useful services (e.g. Collections.sort , Collections.shuffle ) • Set : an unordered collection that does not permit duplicate elements • Framework: Programmers can supply additional data structures, services • SortedSet : a set whose elements are visited in • New data structures automatically work with sorted order services • New services automatically work with data • List : an ordered collection structures Collections Framework: Classes Collections Framework • HashSet : a set implementation that uses hashing to locate the set elements • TreeSet : a sorted set implementation that stores the elements in a balanced binary tree • LinkedList and ArrayList : two implementations of the List interface type
Collection Interface Type Iterator<E> Interface Type • Collection holds elements in some way • Iterator traverses elements of collection • Different data structures have different storage strategies Collection<E> interface has methods: • boolean hasNext() boolean add(E obj) boolean addAll(Collection<? extends E> c) E next() void clear() boolean contains(Object obj) void remove() boolean containsAll(Collection<?> c) boolean equals(Object obj) int hashCode() boolean isEmpty() Iterator<E> iterator() boolean remove(Object obj) boolean removeAll(Collection<?> c) boolean retainAll(Collection<?> c) int size() Object[] toArray() E[] toArray(E[] a) AbstractCollection Class AbstractCollection Class • Collection is a hefty interface • Can't place template methods in interface • Convenient for clients, inconvenient for implementors • Place them in AbstractCollection class • Many methods can be implemented from others (Template method!) • AbstractCollection convenient superclass for • Example: toArray implementors public Object[] toArray() { • Only two methods undefined: size , iterator Object[] result = new Object[ size ()]; Iterator e = iterator (); • add implemented but throws for (int i=0; e.hasNext(); i++) result[i] = e.next(); UnsupportedOperationException return result; } Adding a new Collection to the Recall Queue Framework private Object[] elements; • Use queue from chapter 3 private int count, head, tail; • Supply an iterator (with do- nothing remove method) public boolean add (E anObject) { elements[tail] = anObject; • override add, always returns true tail = (tail + 1) % elements.length; (collection is changed by add) count++; return true; } • addAll etc inherited from public int size () { return count; } AbstractCollection public boolean isFull () {return count == elements.length;} public Object peek () { return (E) elements[head]; } • define size, isFull, peek, public Object remove () { remove E r = (E) elements[head]; head = (head + 1) % elements.length; count--; return r; }
Sets public Iterator<E> iterator () { return new Iterator<E>() { public boolean hasNext () { return visited < count; • interface Set<E> extends } Collection<E> public E next () { int index = (head + visited) % elements.length; • Set interface adds no methods to Collection ! E r = (E) elements[index]; visited++; • Conceptually, sets are a subtype of collections return r; } • Sets don't store duplicates of the same element public void remove () { throw new UnsupportedOperationException(); • Sets are unordered } private int visited = 0; • Separate interface: an algorithm can require a }; Set } Lists List Iterators • interface List<E> extends Collection<E> • Indexing • Lists are ordered • Bidirectional behavior • Each list position can be accessed by an integer index • Subtype methods: • ListIterator<E> subtype methods: boolean add(int index, E obj) boolean addAll(int index, Collection<? extends E> c) int nextIndex() E get(int index) int previousIndex() int indexOf(E obj) int lastIndexOf(E obj) boolean hasPrevious() ListIterator<E> listIterator() ListIterator<E> listIterator(int index) E previous() E remove(int index) E set(int index, E element) void set(E obj) List<E> subList(int fromIndex, int toIndex) void add(E obj) List Classes • ArrayList • LinkedList • Indexed access of linked list elements is possible, but slow • Weakness in the design • Partial fix in Java 1.4: RandomAccess interface
Optional Operations Views • View = collection that shows objects that are stored • Many operations tagged as "optional" elsewhere • Example: Collection.add , • Example: Arrays.asList Collection.remove • String[] strings = { "Kenya", "Thailand", "Portugal" }; • Default implementation throws exception List<String> view = Arrays.asList(strings); • Why have optional operations? • Does not copy elements! • Can use view for common services anotherCollection.addAll(view); Views Graph Editor Framework • get / set are defined to access underlying array • Problem domain: interactive editing of • Arrays.asList view has no add / remove operations diagrams • Can't grow/shrink underlying array • Graph consists of nodes and edges • Several kinds of views: read-only • Class diagram: modifyable nodes are rectangles resizable edges are arrows ... • Electronic circuit diagram: • Optional operations avoid inflation of interfaces nodes are transistors, resistors • Controversial design decision edges are wires Graph Editor Framework User Interface • Toolbar on top • Traditional approach: programmer starts • Grabber button for selecting nodes/edges from scratch for every editor type • Buttons for current node/edge type • Menu • Framework approach: Programmer • Drawing area extends graph, node, edge classes • Framework handles UI, load/save, ... • Our framework is kept simple
Recommend
More recommend