Post on 02-Nov-2018
2
Framework
• Set of cooperating classes/interfaces – Structure essential mechanisms of a problem
domain – Programmer can extend framework classes,
creating new functionality • Example: Swing package is framework for
problem domain of GUI programming
3
Frameworks Vs. Patterns
• Pattern: general design rule for solving a problem
• Framework: set of classes providing functionality in a particular domain; often uses multiple patterns
4
Application Frameworks
• Implement services common to any type of application
• Supply sets of classes for programmer to augment to build applications (often by subclassing framework classes)
5
Inversion of Control
• Framework classes, not application-specific classes, control flow of execution
• Framework determines which methods to call and when
6
Framework example: Applets
• Applet: Java program originally intended to run within a web page to add interactions and dynamism
• Java source referenced by an HTML document • Most browsers no longer support applets • Package java.applet is a simple application
framework – consists of superclasses to make applets – programmer adds classes, overrides methods to create
actual applets
7
Applet characteristics
• No main() method • Programmer overrides some or all of the
following methods: – init() – start() – stop() – destroy() – paint()
8
How applets work
• Since an applet has no main() method, initialization of object takes place in method init(), which takes the place of both main() and the constructor
• Method init() is typically used to perform initializations of short duration; longer running initializations, e.g. loading a file across a network, should be done in separate threads
9
Methods of Applet class
• Method init() is empty, and must be overridden by the child class
• Method start() is called to set up the applet to run – may create several threads – called when applet is loaded & initialized the
first time, resized, or when user returns to page from elsewhere
– paint() automatically called after start()
10
Methods of Applet class
• Method stop() is called to stop the applet - usually means halting threads started by start() when, for example, the user leaves the page
• Method destroy() performs final cleanup before the applet is unloaded
11
Methods of Applet class
• Control sequence is: – init() – start() – paint() – then stop() or destroy(), as appropriate
• Applet can transition many times between start() and stop() states
• May define all, some, or none of these methods when extending an Applet; should only define those necessary for specific applet
12
More fun facts about applets
• Applet class is actually subclass of Panel - so inherits graphical component attributes
• Events, in particular, are handled same way as other graphical components, and window repainting same as application
• Default layout for applet is flow layout, not border layout
13
Applets vs. Applications
• An applet has no main method, as it is structured to run inside another application
• The Java Virtual Machine runs applications, but not applets
• Can use appletviewer program to test and debug applet code
• Most applets are event-driven (but don’t have to be)
14
Creating Applet/Application Hybrids
• Applet class pays no attention to static methods contained in class definition
• Key idea is that Applet is a Panel – can nest inner class within Applet to create Frame necessary for
application – only component created for this Frame will be Panel constructed
by Applet – Method main(), which is ignored when executing as applet, creates
instance of applet when run as an application – Applet then creates instance of Frame, placing itself in center – Constructor for Frame executes requisite init() and start()
15
Applets as Framework
• Programmer for individual applet uses inheritance to extend the applet framework class to specific program
• Applet class deals with behavior common to all applets; programmer only fills in custom behavior for specific application
16
Applets as Framework
• Inversion of control means applet programmer not concerned with overall control flow - fills in handlers for initialization, starting, stopping and painting, but has no control over when these methods are called
Frameworks in the Java API • As we have just seen, the Applet framework
is one example from the Java API; the entire set of swing classes is another (but much larger, won’t fit on one screen)
17
Java Collections Framework
• Collection: an object that contains a group of objects
• Java API contains library of useful data structures to describe various Collection types
• Collections library also serves as framework for adding new collection classes that can interact with existing classes
18
Java Collections Framework
• Collections framework specifies four interfaces: – Collection: general collection (bag) – Set: unordered collection of unique elements – SortedSet: ordered collection of unique elements – List: ordered collection of elements; can contain duplicates
• Several concrete classes as well - some examples: – HashSet and TreeSet: set implementations that use hashing and
balanced binary treess, respectively to store the set elements – LinkedList and ArrayList: implementations of the List interface
19
21
Collection and Iterator
• Collection and Iterator are the fundamental interfaces of the collections framework
• A collection is any class that can store multiple elements; individual collection classes enforce different rules for how data are to be stored and located
• An iterator is a mechanism for visiting all elements in a collection
22
Methods specified by Collection interface
boolean add(Object obj) boolean addAll(Collection c) void clear() boolean contains(Object obj) boolean containsAll(Collection c) boolean equals(Object obj) int hashCode()
boolean isEmpty() Iterator iterator() boolean remove(Object obj) boolean removeAll(Collection c) boolean retainAll(Collection c) int size() Object[] toArray() Object[] toArray(Object[] a
23
AbstractCollection class
• Collection is a hefty interface: client programmer must implement 15 methods
• AbstractCollection class relieves client programmer of this burden; provides reasonable default implementations for almost all of these methods
24
Example method from AbstractCollection
public Object[] toArray() { Object[] result = new Object[size()]; Iterator e = iterator(); for (int i=0; e.hasNext(); i++) result[i] = e.next(); return result; }
Note use of size() and iterator(); these are the two methods left undefined by the abstract class. Which pattern is in play here?
25
Notes on AbstractCollection
• Methods like toArray() implement the template method pattern; since they are implementations, not just specifications, they must appear in a class
• Methods size() and iterator() are left undefined by AbstractCollection; most concrete collections derived from this class also override add() and remove()
26
Adding new class to Collections framework
• Text uses example of Queue class; originally developed in chapter 3 without connection to framework
• Why use framework? – Framework provides a number of methods that work on
all Collections; addAll(), for example, does bulk addition of all elements from one collection to another
– If Queue is part of framework, such methods are automatically applicable to the new class
27
Optional operations
• API documentation tags some methods as optional operations
• Default implementations throw UnsupportedOperationException
• Collection methods add() and remove() are examples
28
Views
• View: object that implements an interface of collections framework, but permits only restricted access to data structure
• Optional operations exist to support views • Built-in Java type array has no methods; can apply
view to enhance array functionality
29
Views
• Example: asList method – asList turns an array into a view object: collection that
implements List interface, so List methods can be applied to array elements
– does not copy array elements; get and set methods of view object access original array
– Can’t apply add() or remove() methods to view, because size of underlying array can’t be changed: this is why these methods are “optional”
Beyond the API: Greenfoot
• Greenfoot: a framework for teaching Java programming to beginners – From the makers of BlueJ – Problem domain is simple game programming
30
33
Graph editor framework
• Problem domain: interactive editing of graphs
• Graph: collection of nodes and edges arranged in certain shape
• Examples of graphs: – class relationship diagrams – electronic circuit diagrams – flow charts
34
Graph editor framework
• Encapsulates aspects common to all graph editing applications – user interface – event handling
• Application programmer extends graph editor framework, defines specific behavior for nodes and edges
36
User interface Toolbar includes: • grabber tool for selecting elements • buttons for each node/edge type • menus:
• loading/saving diagram • deleting selected elements
Drawing area: • Mouse used for drawing; behavior depends on current tool:
• if node, clicking empty space inserts new node • if grabber, clicking on element selects it; dragging operation moves selected node & connected edges • if edge, drag from one node to another inserts edge
37
Division of responsibility
• Drawing shapes of nodes & edges: application
• Hit testing (element hit by mouse click): application
• Drawing toolbar: framework • Mouse listening: framework
38
Division of responsibility
• Application programmer must inform framework about node & edge types of particular graph type – concrete graph gives framework prototype objects – toolbar queries graph for prototypes, adds buttons for
each one – nodes & edges draw themselves in paintIcon method of
button icon object – when user inserts new node or edge, object
corresponding to selected tool is cloned & added to graph
39
Prototype pattern
• Teaches how a system can instantiate classes that are not known when system is built
• Nature of node & edge types unknown when framework code is designed - use prototype pattern to solve this problem
40
Prototype pattern
• Context: – A system instantiates objects of classes that are
not known when the system is built. – You do not want to require a separate class for
each kind of object. – You want to avoid a separate hierarchy of
classes whose responsibility it is to create the objects.
41
Prototype pattern
• Solution: – Define a prototype interface type that is
common to all created objects. – Supply a prototype object for each kind of
object that the system creates. – Clone the prototype object whenever a new
object of the given kind is required.
43
Prototype pattern applied to graph editor
• Name in pattern: – Prototype – ConcretePrototype1 – Creator
• Name in graph editor: – Node – CircleNode – Instance of GraphPanel
that handles mouse operation for adding new nodes
44
Framework classes
• Node and Edge interfaces include methods: – draw(): used in painting graph – contains(): tests whether mouse click falls
within range of an element – getBounds(): returns rectangle enclosing
element – clone(): clones prototypes when inserting new
elements
45
Framework classes
• Edge interface includes methods getStart() and getEnd() which return nodes connected by edge
• Node interface method getConnectionPoint() returns optimal attachment point for edge
• Edge method getConnectionPoints() yields 2 end points of edge; used by grabbers to mark currently selected edge
• Framework also supplies AbstractEdge class for programmer convenience
46
Framework classes
• Graph class: – collects nodes and edges – has methods for adding, removing, finding and
drawing nodes and edges – is abstract; subclasses must override methods
that populate the toolbar: public abstract Node[] getNodePrototypes() public abstract Edge[] getEdgePrototypes()
47
Framework classes
• GraphFrame class manages the toolbar, menu bar, and graph panel
• Toolbar class holds toggle buttons for node and edge icons
• GraphPanel class displays graph, handles mouse events for editing commands