Frameworks OOD Course Solange Karsenty 1 Frameworks n

  • Slides: 52
Download presentation
Frameworks OOD Course Solange Karsenty

Frameworks OOD Course Solange Karsenty

1 Frameworks n n n “A reusable, semi-complete application that can be specialized to

1 Frameworks n n n “A reusable, semi-complete application that can be specialized to produce a custom application” “A set of cooperating abstract and concrete classes that makes up a reusable design for a specific class of software” An Object-Oriented Reuse Technique ¨ Design Reuse + Code Reuse

A Tiny Example: Calculators ¨ interface n n n get. Value(), compute(Operator o), clear(),

A Tiny Example: Calculators ¨ interface n n n get. Value(), compute(Operator o), clear(), undo() Uses Command pattern, optionally Singleton Remembers parentheses, can iterate on their tree ¨ interface n n n ¨ All Operator Descendants: Unary. Operator, Binary. Operator Concrete classes: Plus, Minus, Power, … Acts as Command class, supports Composites ¨ interface n Calculator Visual. Calculator Observer on Calculator, can display operators on buttons, can display current computation tree are extendible, “Main” receives interfaces

Designing an OO Framework n Domain Knowledge ¨ What applications is the framework for?

Designing an OO Framework n Domain Knowledge ¨ What applications is the framework for? ¨ What is common to all of them? n Architecture ¨ Biggest, most critical technical decisions ¨ What is required besides classes? n Object-oriented design ¨ Design Reuse: Patterns ¨ Inversion of Control + Find right hooks

Domain Knowledge n n a. k. a. Analysis or Modeling Common “significant” decisions: ¨

Domain Knowledge n n a. k. a. Analysis or Modeling Common “significant” decisions: ¨ Major concepts of the modeled domain ¨ Major operations ¨ Use cases: How users do common tasks n For example, a calculator ¨ Concepts: unary operator, binary operator, current value, in-memory value, shift key ¨ Operations: Clear, use operator, compute ¨ Use case: Computing an average of n numbers

5 Architecture n n The set of significant decisions about the structure of software,

5 Architecture n n The set of significant decisions about the structure of software, the division to components and subsystems and their interfaces, and guidelines to composing them Common “significant” decisions: n n n n Programming language, operating system, hardware Use of major external libraries or applications Physical Distribution, processes and threads Main Concepts: Kinds of modules and interfaces Communication and synchronization between modules Security Model Performance and scalability

For Example: JCA n Java Cryptography Architecture (JCA, JCE) n n n Encryption, Digital

For Example: JCA n Java Cryptography Architecture (JCA, JCE) n n n Encryption, Digital Signatures, Key Management Open for new algorithms, new implementations Main Concepts n n Provider: provides implementations for a subset of the Java Security API, identified by name Engine Classes: functionality for a type of crypto behavior, such as Signature and Key. Pair. Generator Factory Methods: static methods in engine classes that return instances of them for a given algorithm Key Store: System identity scope

JCA II n Generating a public/private key pair: n n n Key. Pair. Generator

JCA II n Generating a public/private key pair: n n n Key. Pair. Generator keygen = Key. Pair. Generator. get. Instance(“DSA”, “MY_PROVIDER”); keygen. initialize(key. Size, new Secure. Random(user. Seed)); Key. Pair pair = keygen. generate. Key. Pair(); Cast to DSAKey. Pair. Generator is required to initialize it with algorithm-specific parameters (p, q, g) Generating a signature: n n n Signature sha = Signature. get. Instance(“SHA-1”); Private. Key priv = pair. get. Private(); sha. init. Sign(priv); byte[] sig = sha. sign(); Provider is optional in get. Instance()

JCA III n n Although implementations will usually be non. Java, they must be

JCA III n n Although implementations will usually be non. Java, they must be wrapped in Java classes Statically, add lines to java. security text file ¨ Security. provider. Name. n = com. acme. provider. Package ¨ n is the preference order of the provider, 1 is highest n Providers can be managed dynamically too: ¨ Class Security has add. Provider(), get. Provider() ¨ Class Provider has get. Name(), get. Version(), get. Info() n Providers must write a “Master class” ¨ Specifies which implementations are offered by it ¨ There are standard names for known algorithms

JCA IV: Summary n So what does the architecture answer? ¨ Domain Knowledge: What

JCA IV: Summary n So what does the architecture answer? ¨ Domain Knowledge: What behavior (engine classes) should be supported at all? ¨ How are different algorithms and different implementations defined and selected? ¨ How should non-Java implementations be used? ¨ How can an administrator configure a key store and a trusted set of providers and implementations? ¨ How can commercial companies sell Java-compatible closed-source implementations of security features n Not only classes and interfaces ¨ Persistent key store, config files, non-Java code ¨ Practical, management and economic considerations

Inversion of Control n n n a. k. a. The Hollywood Principle Don’t call

Inversion of Control n n n a. k. a. The Hollywood Principle Don’t call us, we’ll call you Benefits ¨ Code reuse: Flow of control is coded once ¨ Makes it clear when and how hooks are called ¨ Produces uniformity in program behavior, which makes it easier to understand n Drawbacks ¨ Debugging is more difficult ¨ Integrating two frameworks can be hard

Hooks n Hook = Hotspot = Plug-point ¨ Points n where the FW can

Hooks n Hook = Hotspot = Plug-point ¨ Points n where the FW can be customized Design issues requiring domain knowledge ¨ How to find the right hooks? ¨ Few or many hooks? ¨ What should be the default behavior? n Implementation alternatives ¨ Template Method ¨ Strategy or Prototype (Prototype: creational design ; the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects) ¨ Observer

Framework Colors n White-Box Frameworks ¨ Extended by inheritance from framework classes ¨ Template

Framework Colors n White-Box Frameworks ¨ Extended by inheritance from framework classes ¨ Template Method, Builder, Bridge, Abstract Factory ¨ Require intimate knowledge of framework structure n Black-Box Frameworks ¨ Extended by composition with framework classes ¨ Strategy, State, Visitor, Prototype, Observer ¨ More flexible, slightly less efficient n Gray-box Frameworks ¨ What usually happens in real life…

Framework Colors II n n Frameworks tend to evolve to being black-box AWT 1.

Framework Colors II n n Frameworks tend to evolve to being black-box AWT 1. 0 had a white-box event model ¨ Each visual component had an handle. Event() method ¨ Each frame inherited and overrode it ¨ The method was a long switch statement n AWT 1. 1 and Swing are black-box ¨ Observer pattern: UI components publish events to registered listeners n Why is black-box better? ¨ Separation of concerns: better abstractions ¨ Important for (automatic) code generation

June 14, 2006 14 Designing an OO Framework n Domain Knowledge ¨ What applications

June 14, 2006 14 Designing an OO Framework n Domain Knowledge ¨ What applications is the framework for? ¨ What is common to all of them? n Architecture ¨ Biggest, most critical technical decisions ¨ What is required besides classes? n Object-oriented design ¨ Design Reuse: Patterns ¨ Inversion of Control + Find right hooks

June 14, 2006 15 Application Domains n System Infrastructure ¨ Operating System Wrappers: MFC,

June 14, 2006 15 Application Domains n System Infrastructure ¨ Operating System Wrappers: MFC, Mac. App ¨ Communication Protocols: RMI ¨ Database Access: ADO, JDO ¨ Security: JCA, JSA n User Interfaces ¨ Small. Talk-80 is the first widely used OOFW ¨ Swing, Delphi, MFC, COM… ¨ Integrated with development environments

June 14, 2006 16 Application Domains II n Middleware / Object Request Brokers ¨

June 14, 2006 16 Application Domains II n Middleware / Object Request Brokers ¨ Object Request Brokers: CORBA, COM+, EJB ¨ Web Services: . NET, Sun One n Enterprise Applications ¨ Enterprise = Critical to day-to-day work ¨ Usually developed inside organizations ¨ Notable Exception: IBM’s San-Francisco ¨ Java-based, reusable, object-oriented business components for commercial applications, along with an execution framework ¨ Telecomm, Manufacturing, Avionics, Finance, Insurance, Healthcare, Warehouses, Billing…

Framework Strengths n Reuse, Reuse! ¨ Design n + Code Extensibility ¨ Enables n

Framework Strengths n Reuse, Reuse! ¨ Design n + Code Extensibility ¨ Enables n Enforced Design Reuse ¨ An n the creation of reusable Components “Educational” Tool Partitioning of Knowledge & Training ¨ Technical vs. Applicative Specialization

Framework Weaknesses n Development effort ¨ Generic frameworks are harder to design and build

Framework Weaknesses n Development effort ¨ Generic frameworks are harder to design and build ¨ They are also hard to validate and debug n Maintenance ¨ Does the FW or the app need to change? ¨ Interface changes require updating all apps n Learning Curve ¨ Unlike class libraries, you can’t learn one class at a time n n n Integratibility of multiple frameworks Efficiency Lack of standards

June 14, 2006 19 There’s Big Money Involved n All “big players” develop and

June 14, 2006 19 There’s Big Money Involved n All “big players” develop and sell FWs ¨ So you must use our language (Swing) ¨ So you must use our operating system (MFC) ¨ So you must use our development tool (Delphi) ¨ So you must use our database (Oracle) n There’s a component industry too ¨ Companies n that write and sell components Frameworks are an economic necessity ¨ Unwise to develop UI, DB, ORB alone today

Frameworks: Swing Case Study

Frameworks: Swing Case Study

Swing n Java’s User Interface FW since JDK 1. 2

Swing n Java’s User Interface FW since JDK 1. 2

June 14, 2006 22 The Problem n n Hardware and operating system support primitive

June 14, 2006 22 The Problem n n Hardware and operating system support primitive I/O operations Drawing pixels and lines on the screen ¨ Class java. awt. Graphics has draw. Line(), set. Color(), fill. Rect(), set. Font(), … methods n Receiving user input ¨ Reading file and device input streams ¨ Platform-dependent

The Problem II n Visual components are not reused ¨ Should be in standard

The Problem II n Visual components are not reused ¨ Should be in standard library ¨ Look-and-feel should be consistent ¨ Easy to create / buy new visual components n Design of user interface is not reused ¨ Separating visual design, data structures, user input handling and applicative code n n Code is not platform-independent A lot of code & design is required

Swing Features n Wide variety of visual components ¨ Button, Label, List, Panel, Table,

Swing Features n Wide variety of visual components ¨ Button, Label, List, Panel, Table, Tree, … ¨ Standard Dialog Boxes (Open, Save, Color, …) n Pluggable look-and feel ¨ Platform independence ¨ Dynamically changeable n MVC architecture ¨ Facilitates n writing components or look-and-feels Action objects ¨ Shared commands in toolbars and menus ¨ Generic Undo capability

Swing Features II n Keystroke Handling ¨ Global, form, container and component shortcuts ¨

Swing Features II n Keystroke Handling ¨ Global, form, container and component shortcuts ¨ Conflict management n Nested Containers ¨ Windows, Dialogs, Frames, Panels, Tables, … ¨ Virtually anything can be in anything, at any depth n Text Manipulation ¨ HTML n and RTF editing (multi-font, colors, etc. ) Accessibility ¨ Alternative user interface support: Braille, sound…

A Simple Form The application will show this dialog box: l n n We’ll

A Simple Form The application will show this dialog box: l n n We’ll use JButton and JText. Field Inside a JPanel container Inside a JFrame (a window container) Whose main() method will run the show

27 The Simple Form Code n Step 1 is to subclass JPanel: ¨ class

27 The Simple Form Code n Step 1 is to subclass JPanel: ¨ class Simple. Panel extends JPanel { JText. Field text. Field; JButton button; public Simple. Panel() { button = new JButton("Clear Text"); add(button); text. Field = new JText. Field(10); add(text. Field); button. add. Action. Listener(new Action. Listener() { public void action. Performed(Action. Event e) { text. Field. set. Text(""); } }); }}

The Simple Form Code II n Step 2 is to subclass JFrame: ¨ public

The Simple Form Code II n Step 2 is to subclass JFrame: ¨ public class Simple. Panel. Test extends JFrame { static final int WIDTH = 300; static final int HEIGHT = 100; Simple. Panel. Test(String title) { super(title); Simple. Panel simple. Panel = new Simple. Panel(); Container c = get. Content. Pane(); c. add(simple. Panel, Border. Layout. CENTER); }

The Simple Form Code III n The same class also contains main(): ¨ n

The Simple Form Code III n The same class also contains main(): ¨ n public static void main(String args[]) { JFrame frame = new Simple. Panel. Test("Simple. Panel Example"); frame. add. Window. Listener(new Window. Adapter() { public void window. Closing(Window. Event e) { System. exit(0); } }); frame. set. Size(WIDTH, HEIGHT); frame. set. Visible(true); } } The framework takes over after main()

30 Swing Framework Structure n https: //appframework. dev. java. net/intro/index. html

30 Swing Framework Structure n https: //appframework. dev. java. net/intro/index. html

31 Using the Framework n To write an application, you need to do just

31 Using the Framework n To write an application, you need to do just a few things: ¨ Extend the Application class and override its startup() method. Your startup method should create and show the application's initial GUI. ¨ when the user closes the last top level window, call Application. exit(). This causes the application's exit. Listeners to run and eventually calls Application. shutdown(). ¨ In your main method, call the static Application. launch method. This constructs and starts your Application subclass on the event dispatching thread. https: // ¨ Ref: appframework. dev. java. net/intro/index. html http: //www. netbeans. org/kb/60/java/gui-saf. html

32 Example public class Application. Example 1 extends Application { JFrame main. Frame =

32 Example public class Application. Example 1 extends Application { JFrame main. Frame = null; @Override protected void startup(String[] ignore. Args) { JLabel label = new JLabel("Hello World", JLabel. CENTER); label. set. Font(new Font("Lucida. Sans", Font. PLAIN, 32)); main. Frame = new JFrame(" Hello World "); main. Frame. add(label, Border. Layout. CENTER); main. Frame. add. Window. Listener(new Main. Frame. Listener()); main. Frame. set. Default. Close. Operation(JFrame. DO_NOTHING_ON_CLOSE); main. Frame. pack(); main. Frame. set. Location. Relative. To(null); // center the window main. Frame. set. Visible(true); } private class Main. Frame. Listener extends Window. Adapter { public void window. Closing(Window. Event e) { exit(e); } } public static void main(String[] args) { launch(Application. Example 1. class, args); } }

The Framework in Action n Inversion of Control ¨ Event loop is handled by

The Framework in Action n Inversion of Control ¨ Event loop is handled by a Swing thread ¨ Hardware- and OS-specific input formats are translated to standard interfaces n Hooks ¨ Building the visual controls is white-box style ¨ Registering to events is black-box style n Design Patterns ¨ Composite: JPanel. add(Component c) ¨ Observer: JButton. add. Action. Listener(al)

Patterns in Swing n Command ¨ All text editors shared some commands (cut, paste)

Patterns in Swing n Command ¨ All text editors shared some commands (cut, paste) ¨ These are encapsulated in Action objects ¨ Each text components supports get. Actions() ¨ Action objects are globally shared, and are used on menu items, toolbars and shortcuts n Strategy ¨ The Look. And. Feel interface has several heirs ¨ The UIManager singleton points to the current one ¨ It has methods to dynamically change look and feel

35 (command: reminder) objects are used to represent actions

35 (command: reminder) objects are used to represent actions

36 (strategy: reminder) algorithms can be selected at runtime

36 (strategy: reminder) algorithms can be selected at runtime

Pluggable Look and Feel 37

Pluggable Look and Feel 37

Pluggable Look and Feel String os. Name=System. get. Property("os. name"); Look. And. Feel app.

Pluggable Look and Feel String os. Name=System. get. Property("os. name"); Look. And. Feel app. Look. And. Feel; if (is. Match("Windows", os. Name)) { app. Look. And. Feel=new Windows. Look. And. Feel(); } else if (is. Match("Solaris", os. Name)) { app. Look. And. Feel=new Motif. Look. And. Feel(); } //. . . other cases else { app. Look. And. Feel=new Metal. Look. And. Feel(); } UIManager. set. Look. And. Feel(app. Look. And. Feel); 38

Patterns in Swing II n State ¨ JEditor. Pane is a visual editor that

Patterns in Swing II n State ¨ JEditor. Pane is a visual editor that supports reading and writing files in multiple formats ¨ Each format is represented by an Editor. Kit that registers with the JEditor. Pane ¨ Upon reading a file, its format is used to select an Editor. Kit for it ¨ That kit is used to read, write, list actions, … n Prototype ¨ Editor Kits are created by cloning the prototype ¨ However, this is done by reflection on class name

Patterns in Swing III n Builder ¨ Editor Kits act as builders: their input

Patterns in Swing III n Builder ¨ Editor Kits act as builders: their input is the hierarchical Document interface ¨ Their output is the View interface: has paint method, can layout, translate coordinates, … n Abstract Factory ¨ interface View. Factory creates views ¨ Two heirs: HTMLView. Factory, Basic. Text. UI ¨ Another singleton n Factory Method ¨ Editor kits use factory methods to facilitate changing parser, view factory and default document

Patterns in Swing IV n n Chain of Responsibility ¨ A Key. Map is

Patterns in Swing IV n n Chain of Responsibility ¨ A Key. Map is a <Key. Stroke, Action> map ¨ A text component has one or more Keymaps ¨ Custom Keymaps can be added and removed ¨ Keymap matching is by most-specific-first Command ¨ ¨ Package javax. swing. undo offers Undoable. Edit Also Abstract. Undoable. Edit and Compound. Edit classes Class Undo. Manager manages done commands Extends Compound. Edit - supports add. Edit(), undo(), redo(), set. Limit(), trim. Edits(), undo. To(), redo. To(), … 41

Model / View / Controller n The Basic User Interface Design Pattern ¨ Origin

Model / View / Controller n The Basic User Interface Design Pattern ¨ Origin is Small. Talk 80, the first OOFW

MVC Participants n Model ¨ Data structure of displayed data ¨ Notifies observers on

MVC Participants n Model ¨ Data structure of displayed data ¨ Notifies observers on state change n View ¨ Paints the data on the screen ¨ Observer on its model n Controller ¨ Handles user input ¨ Changes model, which causes views to update

MVC Benefits n n Three elements can be reused separately Synchronized user interface made

MVC Benefits n n Three elements can be reused separately Synchronized user interface made easy ¨ Multiple n views observe one model Models know nothing about presentation ¨ Easy to modify or create views ¨ Easy to dynamically change views n More efficient ¨ Shared models & controllers save memory ¨ Easy to maintain pools of views and models

Document / View n View and Controller are often merged MFC: “Document” and “View”

Document / View n View and Controller are often merged MFC: “Document” and “View” ¨ Swing (Text Editors): “Document” and “View” ¨ Swing (Components): “Model” and “UI” ¨

MVC Inside a Component n Each component is a façade for two objects ¨

MVC Inside a Component n Each component is a façade for two objects ¨ Each components defines get. Model() and get. UI() ¨ Usually one component per model and delegate n UIManager is a singleton ¨ Holds n current look & feel properties Component. UI defines drawing interface ¨ javax. swing. plaf. * includes Button. UI, Slider. UI, …

Swing and MVC n n There are several levels of using MVC “Manually”, to

Swing and MVC n n There are several levels of using MVC “Manually”, to synchronize complex views ¨A n file explorer, with a tree and current dir In forms or complex components ¨ Custom form logic to synchronize its field ¨ A table or tree and its sub-components ¨ A variation of the Mediator design pattern n Event-handling at the application level

48 The Façade Pattern n A flexible framework becomes very complex It is important

48 The Façade Pattern n A flexible framework becomes very complex It is important to provide simple façades JEditor. Pane class ¨ No need to know Editor. Kit & its subclasses, Document, Element, View. Factory, Key. Map, … n JButton class ¨ No need to know Component. Model, Component. UI, UIManager, Look. And. Feel, … n Provide users only with concepts they know ¨ Button, Window, Action, Menu ¨ X Document, View. Factory, Editor. Kit

49 The Façade Pattern Facade: The facade class interacts Packages 1, 2, and 3

49 The Façade Pattern Facade: The facade class interacts Packages 1, 2, and 3 with the rest of the application. Clients: The objects using the Facade Pattern to access resources from the Packages: Software library / API collection accessed through the Facade Class.

June 14, 2006 50 Other Features n Swing supports several other features that we

June 14, 2006 50 Other Features n Swing supports several other features that we don’t have time to cover: ¨ Drag & Drop ¨ Printing ¨ Internationalization ¨ Trees and Tables ¨ Menus & Popup menus ¨ Layout Management n Other standard Java graphic libraries: ¨ 2 D drawing, 3 D drawing, Multimedia Object Oriented Design

Summary n Swing is a classic OOD framework ¨ Contains a lot of domain

Summary n Swing is a classic OOD framework ¨ Contains a lot of domain knowledge ¨ Highly customizable through design patterns ¨ Comes with a set of implemented components ¨ Also intended for writing new ones ¨ Inversion of control + hooks n It’s a medium-sized framework ¨ Several hundred classes and interfaces ¨ Plus free & commercial 3 rd party components