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

Slides:



Advertisements
Similar presentations
 Specifies a set of methods (i.e., method headings) that any class that implements that interface must have.  An interface is a type (but is not a class).
Advertisements

Object Oriented Programming Lecture 7: Algorithm animation using strategy and factory patterns, The Adapter design pattern
Patterns Lecture 2. Singleton Ensure a class only has one instance, and provide a global point of access to it.
Applets. The Applet Class public class MyApplet extends java.applet.Applet {... /** The no-arg constructor is called by the browser when the Web page.
Review of Java Applets Vijayan Sugumaran Decision and Information Sciences Oakland University.
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)
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 14 Applets, Images,
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L05 (Chapter 16) Applets.
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.
Applets  The Applet Class  The HTML Tag F Passing Parameters to Applets.
Chapter 12 Applets and Advanced Graphics  The Applet Class  The HTML Tag F Passing Parameters to Applets F Conversions Between Applications and Applets.
Inheritance & Interfaces. The Plan ● Motivate Inheritance ● Motivate Interfaces ● Examples ● Continue Practice on Observer/Observable.
Object Oriented Programming Lecture 8: Introduction to laboratorial exercise – part II, Introduction to GUI frames in Netbeans, Introduction to threads.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
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.
Quiz 1 What is this? (explain the use of the reserved word “this” in a class method). Answer each question briefly. – What is a Constructor? –Under what.
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.
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.
Field Trip #19 Animations with Java By Keith Lynn.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
COMP 321 Week 2. Outline Event-Driven Programming Events, Event Sources, Event Listeners Button and Timer Events Mouse Events, Adapters.
Chapter 7: Pinball Game Construction Kit. Vectors Example of a “collection class” Must “import java.util.Vector” More flexible than arrays: will grow.
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.
Object Oriented Programming.  Interface  Event Handling.
Intro to Applets. Applet Applets run within the Web browser environment Applets bring dynamic interaction and live animation to an otherwise static HTML.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Proxy Pattern defined The Proxy Pattern provides a surrogate or placeholder for another object to control access to it by creating a representative object.
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.
1/18H212Mouse and Timer Events H212 Introduction to Software Systems Honors Lecture #16: Mouse and Timer Events October 26, 2015.
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.
Design Patterns. Outline Purpose Purpose Useful Definitions Useful Definitions Pattern Overview Pattern Overview.
Jaeki Song ISQS6337 JAVA Lecture 10 Applets. Jaeki Song ISQS6337 JAVA Applet Applets run within the Web browser environment –Applets bring dynamic interaction.
UQC117S2 Graphics Programming Lecture 2 Event Handling Program as a sequence of instructions Event -driven program Need to detect the event and carry out.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Events and Event Handling
Java Applets.
Design Patterns: MORE Examples
Common Design Patterns
GUI Event Handling Nithya Raman.
Java Applets.
Chapter 8, Design Patterns Factory
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

1 Object Oriented Programming Lecture XII The Adapter,Template, Strategy and Factory design patterns

2 Last Lecture More design by abstraction –Design patterns the Strategy pattern (again) –Making use of interfaces the Factory pattern –making use of abstract classes and inheritance the Adapter design pattern –A concrete case study An algorithm animator Applying the Template, Strategy, Observer-Observable and the Factory patterns

3 Today’s Talk Concurrency by multithreading –Design patterns the Strategy pattern (again) –Making use of interfaces the Factory pattern –making use of abstract classes and inheritance the Adapter design pattern –A concrete case study An algorithm animator Applying the Template, Strategy, Observer-Observable and the Factory patterns

4 Template Pattern Purpose: To implement a generic, reusable Class which: –encapsulates shared and necessary functionality i.e. concrete methods in Java –but also allowing specific methods to be user specified (abstract in the template) the abstract keyword enforce user definition of these methods We have used the Template pattern in –the generic Doublebuffered Animation Applet –the generic Function Plotter

5 Structure of the Template pattern Abstract Class Concrete implementations (invariant parts) Abstract hook methods Subclass extending the template (Concrete class) Definition of the methods

6 Strategy pattern Purpose: An abstraction for decoupling of algorithms from its context –to enforce provision of a set of required services (methods) but using different algorithms The abstract strategy specifies the contractual interface A concrete strategy must implement the contractual interface, and provide the definition of a specific strategy A very useful method for dynamic coupling of different algorithms in a program

7 Design Pattern: Strategy The plotter The abstract strategy: An Interface or Abstract Class Concrete implementations

8 Animation of Sorting Algorithms Applet to visualize the execution of sorting algorithms Should be easy to adapt –for different sort algorithms –for different displays Demonstrates usage of –the Factory pattern, –the Strategy pattern –and the Observer - Observable pattern

9 A Framework for Sorting Algorithms Input to the Algorithm Sorter: –an array of integers ( int[] arr ) Ability to choose different sorting algorithms of different complexity –Bubble Sortcomplexity Ο(n 2 ) –Quick Sortcomplexity O(n*log n) –Insertion Sortcomplexity O(n 2 ) –... The framework should also be adaptable to different display strategies –how we visualize the elements to be sorted

10 Generic Algorithm Animation: Design Issues Algorithm abstraction? –Problem: How can we easily change between different algorithms? Integration with animator? –Problem: The screen should be redrawn after each iterative step, when running the algorithm Display abstractions? –Problem: We also need a methodolgy to be able exchange different graphical displays

11 First design of the Algorithm Animator Two design pattern candidates: –Template: Not flexible enough since we want to dynamically assign any sorting algorithm (recall the function multiplotter from last lecture) –Strategy: More flexible since we can decouple the sorting algorithms from the animator We will use the Strategy pattern to separate algorithms from animator

12 Design Pattern: Strategy Abstract strategy for sort algorithms Concrete Sort algorithms So we can render an image between each step in the sort process

13 The Sorting Abstraction An abstract sort method (hook method) –called by the animator to start sorting How do we render each element swap during the sort? –We implement a pause() function! Pause the sorting and render the image after each swap during the sort process All sorting algorithms do swapping of two elements Makes sense to put the swap in the sorting abstraction How do we order animator to render the image after each swap? –use a reference to Animator so we can call by animator.pause(); –or…we can use the Observer-Observable pattern!

14 The sorting abstraction – applying template pattern 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; }

15 A concrete sorting algorithm class BubbleSortAlgorithm extends SortAlgorithm { public 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(); }

16 The algorithm animator The AlgorithmAnimator template –abstract method for initAnimator(); A an applet –implements Runnable and Observer Performs animation of an abstract SortAlgorithm The animation is controlled by –a thread to handle frame delay –the Observer Observable pattern for abstract object interaction

17 The AlgorithmAnimator public abstract class AlgorithmAnimator extends JApplet implements Runnable,Observer{ … protected SortAlgorithm theAlgorithm; protected int [] arr; … public void start(){ if(animationThread == null){ animationThread = new Thread(this); finished = false; animationThread.start(); } public void stop(){ finished = true; } ….

18 The AlgorithmAnimator … public void run(){ theAlgorithm.sort(arr); } final public void update(Observable obs, Object o) { if (!finished) { try{ Thread.currentThread().sleep(delay); }catch(InterruptedException e) {} repaint(); } public void setDelay(int d){ delay = d; } …

19 The AlgorithmAnimator … public final void init() { setDelay(20); scramble(); initAnimator(); theAlgorithm.addObserver(this); } protected abstract void initAnimator(); protected void scramble() { arr = new int[getSize().height / 2]; for(int i = arr.length; --i >= 0;) arr[i] = i; for(int i = arr.length; --i >= 0;) { int j = (int)(i * Math.random()); SortAlgorithm.swap(arr, i, j); } … }

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

21 How can we improve the design? The different sort algorithms are strongly coupled to the specific Animator We want the sorting algorithms to easily be interchangable –deciding what algorithms at startup time We want the client (algorithm animator) to be ”unaware” of the concrete algorithms

22 Improving our design using the Factory Design Pattern We can put 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) The concrete algorithms will be coupled to the Algorithm Factory

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

24 The StaticAlgoFactory class Input: the name of a sorting algorithm (String) Output: A concrete instance of the abstract SortAlgorithm (a product) The contractual interface for AlgoFactories: –abstract SortAlgorithm makeSortAlgorithm(String algName){...} –must be defined by every concrete AlgoFactory –binds the actual algorithm to the animator

25 The Factory public interface SortAlgorithmFactory { SortAlgorithm makeSortAlgorithm(String name); }

26 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(); }

27 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); }

28 Invoking the AlgorithmAnimation applet

29 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!

30 New Design Pattern: Adapter A design pattern that can be used to: –reuse classes which can not be used directly without some modification –narrow interfaces when just needing a small subset of the methods

31 Narrowing with an adapter Some classes have an implementation which do not ”fit” perfectly with the requirements...or we might only need few of the availabe methods, from a class requiring a certain contractual interface to be defined –eg. when listening for mouse actions

32 The MouseAdapter 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 need to override the methods we need from the mouse listener interface

33 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.

34 The MouseAdapter implements MouseListener 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.

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

36 Structure of the Adapter pattern: Class Adapter

37 Structure of the Adapter pattern: Object Adapter