Object Oriented Programming Lecture 7: Algorithm animation using strategy and factory patterns, The Adapter design pattern www.hh.se/staff/jebe/oop2006/main.html.

Slides:



Advertisements
Similar presentations
1 Object Oriented Programming Lecture XII The Adapter,Template, Strategy and Factory design patterns.
Advertisements

Patterns Lecture 2. Singleton Ensure a class only has one instance, and provide a global point of access to it.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 16 Applets.
Abstract Classes An abstract class is a class with partial implementation. It implements behaviors that are common to all subclasses, but defers to the.
Graphics Programming with Inheritance Template pattern (Chap 6, se SceneEditor)
Applet class The Applet class provides the essential framework that enables applets to be run by a web browser Applet do not have main method Applet depend.
Review CSC 171 FALL 2004 LECTURE 21. Topics Objects and Classes Fundamental Types Graphics and Applets Decisions Iteration Designing Classes Testing and.
GUI Event Handling Nithya Raman. What is an Event? GUI components communicate with the rest of the applications through events. The source of an event.
Design Patterns academy.zariba.com 1. Lecture Content 1.What are Design Patterns? 2.Creational 3.Structural 4.Behavioral 5.Architectural 6.Design Patterns.
More OOP Design Patterns
OOP Languages: Java vs C++
Mouse Events. Handling Mouse Events Java provides two listener interfaces to handle mouse events: MouseListener;  MouseListener;  MouseMotionListener.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Chapter 12 Applets and Advanced Graphics  The Applet Class  The HTML Tag F Passing Parameters to Applets F Conversions Between Applications and Applets.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Object Oriented Programming Lecture 8: Introduction to laboratorial exercise – part II, Introduction to GUI frames in Netbeans, Introduction to threads.
Chapter 12 Applets and Advanced GUI  The Applet Class  The HTML Tag F Passing Parameters to Applets F Conversions Between Applications and Applets F.
Programming Languages and Paradigms Object-Oriented Programming.
Object Oriented Programming Lecture 4: Refactoring, An Applet Example, Idiom - Animation applets, Introduction to the Laboratorial exercise www2.hh.se/staff/jebe/oop2005/
More Event Handling Adapters Anonymous Listeners Pop menus Validating User Input.
Cs884(Prasad)java12AWT1 Abstract Windowing Toolkit Support for Graphical User Interface (Event-driven programming)
CS 11 java track: lecture 4 This week: arrays interfaces listener classes inner classes GUI callbacks.
Java GUI’s are event driven, meaning they generate events when the user interacts with the program. Typical events are moving the mouse, clicking a mouse.
Chapter 10: Applets and Advanced Graphics The Applet Class The Applet Class The HTML Tag The HTML Tag Passing Parameters to Applets Passing Parameters.
CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.
SD2071 Games Programming Abstraction, inheritance and interfaces Exceptions Two dimensional arrays Java collections framework Files Aaron Kans.
Object Oriented Programming Lecture 5: Refactoring by Inheritance and Delegation - A simple Design Pattern for animation applets, A Generic Function Plotter.
Previous programs used a JLabel for OUTPUT. Another Swing component that can be used for both user input and output is the JTextfield. Suppose we want.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
L11-12: Design Patterns Definition Iterator (L4: Inheritance)‏ Factory (L4: Inheritance)‏ Strategy (L5: Multiple Inheritance)‏ Composite (L6: Implementation.
Copyright © 2002, Systems and Computer Engineering, Carleton University b-Gui2.ppt * Object-Oriented Software Development Part 18-b Building.
COMP 321 Week 2. Outline Event-Driven Programming Events, Event Sources, Event Listeners Button and Timer Events Mouse Events, Adapters.
An Introduction to Programming and Object Oriented Design using Java 3 rd Edition. Dec 2007 Jaime Niño Frederick Hosch Chapter 18 Integrating user interface.
1 Object Oriented Programming Lecture XI An abstract function plotter, using the Template and the Strategy design patterns.
1 Object Oriented Programming Lecture XII Multithreading in Java, A few words about AWT and Swing, The composite design pattern.
Chapter 10: Applets and Advanced Graphics The Applet Class The Applet Class The HTML Tag The HTML Tag Passing Parameters to Applets Passing Parameters.
UID – Event Handling and Listeners Boriana Koleva
Understand the difference between applets and applications Identify meaningful applet resources for academic subjects Create and demonstrate a basic Java.
Chapter 14 Applets and Advanced GUI  The Applet Class  The HTML Tag F Passing Parameters to Applets F Conversions Between Applications and Applets F.
Intro to Applets. Applet Applets run within the Web browser environment Applets bring dynamic interaction and live animation to an otherwise static HTML.
CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
GUI DYNAMICS Lecture 11 CS2110 – Fall GUI Statics and GUI Dynamics  Statics: what’s drawn on the screen  Components buttons, labels, lists, sliders,
Design Patterns SE464 Derek Rayside images from NetObjectives.com & Wikipedia.
Object-Oriented Software Engineering Using Threads and simple Animation.
Proxy Pattern defined The Proxy Pattern provides a surrogate or placeholder for another object to control access to it by creating a representative object.
CS 180 Problem Solving and Object Oriented Programming Fall 2010 Notes for Week 9: Oct 18-22, 2010 Aditya Mathur Department of Computer Science Purdue.
CS 5150 Software Engineering Lecture 16 Program Design 3.
1 Event Handling – Lecture 4 Prepared by: Ahmad Ramin Rahimee Assistant Professor ICTI.
Laboratory Study November, Demonstrates Life Cycle of an Applet + Mouse Events + Scrolling.
What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event.
CSI 3125, Preliminaries, page 1 Event Handling. CSI 3125, Preliminaries, page 2 Event Handling An Event Change in the state of an object is known as event.
Mouse Events GUI. Types of Events  Below, are some of the many kinds of events, swing components generate. Act causing EventListener Type User clicks.
StarBuzz Coffee Recipe Boil some water Brew coffee in boiling water Pour coffee in cup Add sugar and milk Tea Recipe Boil some water Steep tea in boiling.
UQC117S2 Graphics Programming Lecture 2 Event Handling Program as a sequence of instructions Event -driven program Need to detect the event and carry out.
Csci 490 / Engr 596 Special Topics / Special Projects Software Design and Scala Programming Spring Semester 2010 Lecture Notes.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
Events and Event Handling
Java Applets.
Common Design Patterns
Design Patterns Lecture part 2.
GUI III IS
Design Patterns for Sorting something old in a new light
Programming in Java Event Handling
GUI Event Handling Nithya Raman.
CSE Software Engineering Fall 1999 Updated by J. Brown
Introduction to Computing Using Java
Java Applets.
Chapter 8, Design Patterns Factory
Presentation transcript:

Object Oriented Programming Lecture 7: Algorithm animation using strategy and factory patterns, The Adapter design pattern

Last lecture  Unit testing Structured testing on units (classes) Reduce complexity by incremental testing on small components No clutter in the source code  Demonstration of the JUnit tool Module in Netbeans Exercise 10: using JUnit

Testing in Software development Requirements analysis Design Implementation and unit testing Integration and system testing Maintenance In this OOP Course In the Software engineering course

Template Pattern  Purpose: A generic Class for objects which: Shares functionality (i.e. same concrete methods in Java) But also has some method implementations that need to be different (abstract)  The common methods are encapsulated in the template class  We used Template pattern in the Doublebuffered Animation Applet the Function Plotter

Structure of the Template pattern Abstract Class Concrete implementations (invariant parts) Abstract methods Subclass extending the template (Concrete class) Implements the hookMethods

Strategy pattern  Purpose: An abstraction to decouple algorithms from its host Force provision of a set of required services (methods) but with different implementations  With strategy pattern we can implement contractually compatible classes with different algorithms  A useful methodolgy to dynamically swap algorithms in a program

Design Pattern: Strategy The plotter The abstract strategy Concrete implementations

Animation of Sorting Algorithms  Applet to visualize execution of sorting algorithms  It should be easy to adapt for different sort algorithms different displays  Demonstrates usage of Factory, Strategy and Observer - Observable patterns

Sorting Algorithms  Input to the Algorithm Sorter: an array of Integers  Choosing different sorting algorithms executing with different complexities Bubble SortO(n 2 ) Quick SortO(n*log n) Insertion SortO(n 2 )...  The framework should adapt to different algorithms and different display strategies

Generic Algorithm Animation – Design Issues  Algorithm Abstraction? Problem: How can we easily change between different algorithms?  Integration with Animation during sorting? Problem: The screen should be redrawn after each iterative step, running the algorithm  Display Abstractions? Problem: We will also need a modular way to hook different graphical displays

Starting the design of the Algorithm Animator  Two design pattern candidates: Template – Not flexible since we want to assign any sorting algorithm after compile time (recall the function multiplotter from last lecture) Strategy – More flexible since we can decouple the sort algorithms from the animator  We will use strategy pattern to separate the algorithm from animator

Design Pattern: Strategy The Strategy interface Concrete Sort algorithms So we can render between each sort iteration!

The Sorting Abstraction  Has an abstract sort method Called by the Animator to start sorting  Issue: How do we render the animation between each swap during the sort?  Solution: We implement a pause() function! Will pause the sorting and render after each swap during the sorting process  Since all sorting algorithms involve swapping of two values Makes sense to factor swap into the sorting abstraction  Issue: How do we render the image after each swap? Use a Animator reference to call: animator.pause(); We will use the Observer-Observable pattern!

The sorting abstraction public abstract class SortAlgorithm extends java.util.Observable { abstract void sort(int a[]); protected void pause(){ setChanged(); notifyObservers(); } protected static void swap(int a[], int i, int j) { int T; T = a[i]; a[i] = a[j]; a[j] = T; }

A concrete sorting algorithm class BubbleSortAlgorithm extends SortAlgorithm { void sort(int a[]) { for (int i = a.length; --i>=0; ) for (int j = 0; j<i; j++) { if (a[j] > a[j+1]) swap(a, j, j+1); pause(); }

The algorithm animator  The AlgorithmAnimator template abstract method for initAnimator();  A an applet Implements Runnable and Observer A thread controls frame delay  Performs animation of an abstract SortAlgorithm  The animation is controlled by Thread to handle frame delay The Observer Observable pattern for drawing synchronisation

A Bubble sorter using the AlgorithmAnimator template public class BubbleSorter extends AlgorithmAnimator { protected void initAnimator(){ theAlgorithm = new BubbleSortAlgorithm(); }

How can we improve the design?  The different sort algorithms are strongly coupled to the specific Animator  We want the sorting algorithms be easily interchangable Loading algorithms at startup  We want the client (Algorithm Animator) be unaware of the concrete algorithms

Improving our design using the Factory Design Pattern  We can separate the creation of algorithms in a separate class  We call this class a Factory and it produces products (Sort Algorithms) of a certain type (Sorting Abstraction) Can be abstractly ”hooked” to the animator  The concrete algorithms will be coupled to the Algorithm Factory instead of the Algorithm Animator

The Factory Design Pattern Using Strategy to decouple the algorithms The concrete Factory

StaticAlgoFactory  Input: the name of a sorting algorithm (String)  Output: A concrete instance of the abstract SortAlgorithm (a product)  The Contractual Interface: abstract makeSortAlgorithm(String algName){...} Must be defined by every concrete AlgoFactory Binds the actual algorithm to the animator

The Strategy abstraction of Factory and a concrete implementation public interface SortAlgorithmFactory { SortAlgorithm makeSortAlgorithm(String name); }

A concrete Algorithm Factory public class StaticAlgoFactory implements SortAlgorithmFactory { public SortAlgorithm makeSortAlgorithm(String name) { if ("BubbleSort".equals(name)) return new BubbleSortAlgorithm(); else if ("QuickSort".equals(name)) return new QuickSortAlgorithm(); else return new BubbleSortAlgorithm(); }

Using the improved AlgorithmAnimator import java.awt.*; public class Sort extends AlgorithmAnimator { protected void initAnimator() { String algoName = getParameter("alg"); SortAlgorithmFactory factory = new StaticAlgoFactory(); theAlgorithm = factory.makeSortAlgorithm(algoName); }

Invoking the AlgorithmAnimation applet

Further improvement: Decoupling the SortDisplay  public int getArraySize() method to provide the arraysize so we know the maximum bars we can draw and animate using this display  public void Display(int[] a, Graphics g, Dimension d) The abstract drawing method, to be called by paint  To be implemented as exercise!

New Design Pattern: Adapter  A design pattern that can be used to: reuse classes without modifying the code, instead we convert the interface! narrow interfaces when just needing a small subset of the methods

Simple example: Narrowing of thye MouseListener with MouseAdapter  Some classes have an implementation which does not ”fit” the requirements  Or we might only need few of the availabe methods Ex. listening for mouse actions  MouseAdapter is a class implementing the MouseListener interface The adapter defines all MouseListener methods empty (No action as default) By extending the MouseAdapter we only have to override the methods we need in the mouse listener interface

The MouseListener interface void mouseClicked(MouseEvent e); Invoked when the mouse button has been clicked (pressed and released) on a component. void mouseEntered(MouseEvent e); Invoked when the mouse enters a component. void mouseExited(MouseEvent e); Invoked when the mouse exits a component. void mousePressed(MouseEvent e); Invoked when a mouse button has been pressed on a component. void mouseReleased(MouseEvent e); Invoked when a mouse button has been released on a component.

The MouseAdapter void mouseClicked(MouseEvent e){/* no action */} Invoked when the mouse has been clicked on a component. void mouseEntered(MouseEvent e) {/* no action */} Invoked when the mouse enters a component. void mouseExited(MouseEvent e) {/* no action */} Invoked when the mouse exits a component. void mousePressed(MouseEvent e) {/* no action */} Invoked when a mouse button has been pressed on a component. void mouseReleased(MouseEvent e) {/* no action */} Invoked when a mouse button has been released on a component.

A Simple MouseClick listener Public MouseClick extends MouseAdapter{ void mouseClicked(MouseEvent e){ System.out.println(”Disco!”); } /** * Other MouseListener methods can be omitted **/ }

Structure of the Adapter pattern – Class Adapter

Structure of the Adapter pattern – Object Adapter