C SC 225 Lecture 12: OO Frameworks
[ previous
| schedule
| next ]
Framework Overview
What is an OO Framework?
- Set of related interfaces, abstract classes, and concrete classes
- Set of conventions for implementing the interfaces and extending the classes
- Usually domain-specific but can be domain-neutral
- Support reuse of designs and implementations
- A framework can be considered an application framework with these additional characteristics
- It provides essential mechanisms of an application (Jia: a semicomplete application)
- Client extends the classes and interfaces to build application
- The framework provides inversion of control
Inversion of Control
- A.k.a. "Hollywood Principle: Don't call us, we'll call you."
(www.martinfowler.com/bliki/InversionOfControl.html)
- Here's the inversion: Framework methods call the implementer-(extender)supplied methods instead of vice versa
- Simple example for GUI: You supply custom paint() method but you never call it, the GUI framework does.
- The framework itself controls high level flow within the application
- The user controls low-level flow through input events, framework controls what is available to user
Inversion of control and the Template Method design pattern
- The Template Method design pattern epitomizes inversion of control
- Described in both Horstmann and Head First Design Patterns books
- Use this pattern when: algorithm can be applied to multiple types, and algorithm contains primitive
operations that can differ for each type but the operation sequence is the same for every type.
- Apply this pattern by:
- Defining algorithm as method (the "template method") in abstract superclass; it calls primitive operations (also methods) in particular order
- Defining primitive operations in the abstract superclass as abstract methods or with appropriate default behavior
- Defining primitive operations in concrete subclass(es) as methods to carry out desired behavior
- Head First example: making coffee and making tea: the generic algorithm is the same (boil water, brew, pour into cup, add condiments)
but the details of each step can differ.
- The client of the concrete subclass calls the inherited template method, which polymorphically calls
the appropriate subclass methods to carry out the algorithm.
- The framework provides the first two parts of the pattern solution. The framework extender provides
the third.
How is a framework different than a library?
- Library: application structure is controlled by client and library services are subservient.
- Framework: application structure is controlled by framework, and client fills in details
How are frameworks different than design patterns?
- Frameworks are more concrete; they are code that is already compiled and ready to use
- Design patterns are more abstract, just like design is, and are language independent
- Design patterns are incorporated into design of framework (see Template Method above)
- Framework thus benefits from design pattern benefits: extensibility, reusability
What qualities should a framework have?
It may help to think of an example, such as Java’s Collection classes.
Jia textbook recites these qualities, with credit, from Booch’s classic 1994 OOAD book. I use the term “client” to refer to a developer using the framework.
- Complete: family of classes with common interface, that provide different implementations for client to select from. Think of ArrayList versus LinkedList. What are time/space tradeoffs?
- Efficient: efficient in use of both runtime resources (efficient algorithms), compiler resources, and client resources (easy and reliable to use).
- Type-Safe: uses exceptions to indicate violation of client’s end of contract.
- Simple: clear organization and interface
- Extensible: client can add classes without compromising “architectural integrity” of framework
Java Collections Framework as example framework
Overview
Collection Interfaces
- Common interfaces for the different kinds of collections.
- Polymorphic foundations.
- Headed by java.util.Collection, and java.util.Map
- (technically, Collection is a sub-interface of Iterable)
- Collection categories (sub-interfaces) include: List, Queue, Set, SortedSet
- A list is ordered, with duplicates
- A set may or may not be ordered, no duplicates
- A queue is a collection for “holding elements prior to processing”
- Map interface is separate hierarchy
- A map is an unordered collection of key-value pairs
- Map categories (sub-interfaces) are: ConcurrentMap, SortedMap
General-Purpose Implementations
- The concrete classes that clients use directly.
- All of them implement one or more of the Collection Interfaces.
- Implementations of List concept: LinkedList, ArrayList (when would you use one over the other?)
- Implementations of Set concept: TreeSet, HashSet, LinkedHashSet
- Implementations of Queue concept: PriorityQueue and others
- Implementations of Map concept: TreeMap, HashMap, LinkedHashMap
- Note that name combines implementation technique with concept.
- No “bag” (unordered, duplicates) implementations are provided, client can implement them directly from Collection
Other implementations:
- Lesser-used concrete classes.
- Several categories: Wrapper implementations, convenience implementations, legacy implementations, special purpose implementations
Abstract Implementations
- Partial implementations of the Collection Interfaces.
- Hooks that a client can use to implement custom concrete collection classes.
- Implements the more mundane aspects of the interface so the client doesn’t have to.
- All the concrete implementations above extend one of these
Algorithms
- Common operations that a client might wish to perform over a collection.
- Implemented as static methods in java.util.Collections class (note the plural)
Infrastructure
- Iteration: Iterator and ListIterator
- Ordering: Comparable and Comparator
- Runtime Exceptions: UnsupportedOperationException and ConcurrentModificationException
- Performance: RandomAccess, a “marker interface” that an implementation can use to “advertise” fast (e.g. constant time) random access
Array utilities
- Common operations that a client might wish to perform over an array
- Implemented as static methods in java.util.Arrays
Applets as example application framework
- Applet is Java program that runs inside a Web browser or applet viewer.
- Browser: the bytecode (.class) file is referenced in <applet> tag and loaded from remote server and interpreted by browser
- (aside: compare/contrast with Javascript)
- Applet viewer: Sun provides appletviewer executable (command mode) with J2SE
- java.applet.Applet class has been around since JDK 1.0
- javax.swing.JApplet class extends Applet and was developed as part of Swing
- Basic framework structure:
- The browser/viewer calls certain Applet methods to conduct major business of the applet.
- The certain methods are: init(), start(), stop(), destroy()
- The Applet class provides default definitions of those methods.
- The JApplet class inherits the default methods.
- Applet and JApplet are the API for the framework.
- To define a specific applet, the programmer extends one of these classes and overrides
the inherited methods appropriately.
These excerpts from java.applet.Applet source code show the defaults:
public class Applet extends Panel {
/**
* Called by the browser or applet viewer to inform
* this applet that it has been loaded into the system.
*/
public void init() {
}
/**
* Called by the browser or applet viewer to inform
* this applet that it should start its execution.
*/
public void start() {
}
/**
* Called by the browser or applet viewer to inform
* this applet that it should stop its execution.
*/
public void stop() {
}
/**
* Called by the browser or applet viewer to inform
* this applet that it is being reclaimed and that it should destroy
* any resources that it has allocated.
*/
public void destroy() {
}
}
MARS Tools feature as example framework
Overview
- MARS: Mips Assembler and Runtime Simulator
- MIPS is a popular microcomputer architecture for embedded systems
- See www.mips.com
- MARS is an integrated development environment (IDE) for MIPS assembly language
- Free and downloadable JAR file from www.cs.missouristate.edu/MARS/
- Programmed by Sanderson and Vollmar
MARS Tool
- Feature that allows GUI dialog or frame to interact with executing MIPS program
- Interacts by observing simulated MIPS memory and registers
- A qualifying tool must either
- Implement the mars.tools.MarsTool interface, or
- Extend the mars.tools.AbstractMarsToolAndApplication abstract class
- A concrete class that extends the abstract class can be launched either from Tools menu of MARS or as an application (similar to writing a Java app that can also be run as an applet -- class extends Applet and defines main to call init)
- Abstract class has template methods go() for running as app and action() for running from menu
- Methods called by template method are highlighted in the code excerpt below.
This excerpt from mars.tools.AbstractToolAndApplication source code
shows the template method and default definitions of operations. One is abstract
and must be defined by subclass. Some details are omitted to make the code shorter and easier to follow.
public abstract class AbstractMarsToolAndApplication extends JFrame implements MarsTool, Observer {
/**
* Template method invoked when MARS user selects this tool from the Tools menu.
*/
public void action() {
dialog = new JDialog(Globals.getGui(), this.title);
initializePreGUI();
JPanel contentPane = new JPanel(new BorderLayout(5,5));
contentPane.setBorder(emptyBorder);
contentPane.setOpaque(true);
contentPane.add(buildHeadingArea(), BorderLayout.NORTH);
contentPane.add(buildMainDisplayArea(),BorderLayout.CENTER);
contentPane.add(buildButtonAreaMarsTool(), BorderLayout.SOUTH);
initializePostGUI();
dialog.setContentPane(contentPane);
dialog.pack();
dialog.setVisible(true);
}
/**
* Define this method to initialize any data structures needed for the application
* whose values will be needed to determine the initial state of GUI components.
*/
protected void initializePreGUI() {
}
/**
* Define this method to initialize data structures needed for the application
* whose values may depend on the initial state of GUI components.
*/
protected void initializePostGUI() {
}
/**
* Constructs GUI header as label with default positioning and font. May be overridden.
*/
protected JComponent buildHeadingArea() {
headingLabel = new JLabel();
Box headingPanel = Box.createHorizontalBox();
headingPanel.add(Box.createHorizontalGlue());
headingPanel.add(headingLabel);
headingPanel.add(Box.createHorizontalGlue());
headingLabel.setText(heading);
headingLabel.setHorizontalTextPosition(JLabel.CENTER);
headingLabel.setFont(new Font(headingLabel.getFont().getFontName(),Font.PLAIN,18));
return headingPanel;
}
/**
* Abstract method that must be instantiated by subclass to build the main display area
* of the GUI. It will be placed in the CENTER area of a BorderLayout. The title
* is in the NORTH area, and the controls are in the SOUTH area.
*/
protected abstract JComponent buildMainDisplayArea();
/**
* The MarsTool default set of controls has one row of 3 buttons. It includes a dual-purpose button to
* attach or detach simulator to MIPS memory, a button to reset the tool, and one to close the tool.
*/
protected JComponent buildButtonAreaMarsTool() {
Box buttonArea = Box.createHorizontalBox();
connectButton = new ConnectButton();
connectButton.setToolTipText("Control whether tool will respond to running MIPS program");
connectButton.addActionListener( /* details omitted */ );
JButton resetButton = new JButton("Reset");
resetButton.setToolTipText("Reset all counters and other structures");
resetButton.addActionListener( /* details omitted */ );
JButton closeButton = new JButton("Close");
closeButton.setToolTipText("Close (exit) this tool");
closeButton.addActionListener( /* details omitted */ );
buttonArea.add(connectButton);
buttonArea.add(Box.createHorizontalGlue());
buttonArea.add(resetButton);
buttonArea.add(Box.createHorizontalGlue());
buttonArea.add(closeButton);
return buttonArea;
}
}
[ C
SC 225 | Peter
Sanderson | Math Sciences server
| Math Sciences home page
| Otterbein ]
Last updated:
Peter Sanderson (PSanderson@otterbein.edu)