Copyright W. Howden1 Lecture 14: Callbacks, Singletons and Wrappers.

Slides:



Advertisements
Similar presentations
Copyright W. Howden1 Singleton, Wrapper, and Facade Patterns CSE 111.
Advertisements

Design Patterns Section 7.1 (JIA’s) Section (till page 259) (JIA’s) Section 7.2.2(JIA’s) Section (JIA’s)
Design Patterns CMPS Design Patterns Consider previous solutions to problems similar to any new problem ▫ must have some characteristics in common.
Template, Command, Iterator and Composite CSE 111 5/9/20151Copyright W. Howden.
OOP Design Patterns Chapters Design Patterns The main idea behind design patterns is to extract the high level interactions between objects and.
Copyright W. Howden1 Lecture 7: Functional and OO Design Descriptions.
Copyright W. Howden1 Lecture 3: Elaboration and System Architecture.
Copyright W. Howden1 Lecture 6: Design Evaluation and Intro to OO Design Patterns.
Copyright W. Howden1 Lecture 8: O/O Programming. Copyright W. Howden2 Topics OO Programming Languages Developing programs from Designs –Class and method.
Copyright W. Howden1 Lecture 11: UML Terminology and Additional Models and Notation.
1 Lecture 3: Elaboration and System Architecture.
Copyright W. Howden1 Lecture 19: Intro to O/O Components.
System Architecture Lecture 3 CSE 111 Spring /22/20151Copyright William E. Howden.
More design patterns The ADAPTER Pattern Actions and the COMMAND Pattern Actions and the COMMAND Pattern The FACTORY METHOD Pattern The PROXY Pattern The.
1 Lecture 2: Elaboration Tasks and Domain Modeling.
Satzinger, Jackson, and Burd Object-Orieneted Analysis & Design
Copyright W. Howden1 Lecture 15: Generalization, Polymorphism and States.
Copyright W. Howden1 Lecture 6: Collaboration Diagrams.
Copyright W. Howden1 Lecture 2: Elaboration Tasks and Domain Modeling.
Lecture a: Additional UML Models: Package, Activity, Deployment Lecture b: Generalization, Aggregation and Additional Domain Model Notation Copyright W.
Object-Oriented Analysis and Design
Copyright W.E. Howden1 Lecture 16: Factories and Frameworks.
Copyright W. Howden1 State Models and the State Pattern.
Lecture 7: UML Class Diagrams CSE 111 7/15/20151Copyright W. Howden.
Chapter 26 Applying Gang of Four Design Patterns 1CS6359 Fall 2012 John Cole.
More OOP Design Patterns
Chapter 6: Graphical User Interface (GUI) and Object-Oriented Design (OOD) J ava P rogramming: Program Design Including Data Structures Program Design.
OOP Languages: Java vs C++
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Design Pattern. The Observer Pattern The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all.
GoF Design Patterns (Ch. 26). GoF Design Patterns Adapter Factory Singleton Strategy Composite Façade Observer (Publish-Subscribe)
Objects and Classes Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary.
18 April 2005CSci 210 Spring Design Patterns 1 CSci 210.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
Object Oriented Software Development
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Object Oriented Programming.  Interface  Event Handling.
Programmeerimine Delphi keskkonnas MTAT Programmeerimine Delphi keskkonnas MTAT Jelena Zaitseva
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Gang of Four Patterns 23 total 15 useful How are they different from GRASP Patterns?
Java Programming: From Problem Analysis to Program Design, 3e Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
CSE 332: Design Patterns Review: Design Pattern Structure A design pattern has a name –So when someone says “Adapter” you know what they mean –So you can.
Java Programming: From Problem Analysis to Program Design, Second Edition1 Lecture 5 Objectives  Learn about basic GUI components.  Explore how the GUI.
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
Design Patterns SE464 Derek Rayside images from NetObjectives.com & Wikipedia.
Chapter 5 Classes and Methods II Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas, E.
The Decorator Pattern (Structural) ©SoftMoore ConsultingSlide 1.
More Patterns CS 124. More Basic Patterns Patterns you’ve already seen (without knowing it) Observer / Listener Wrapper Composite Decorator / Filter Patterns.
L10: Model-View-Controller General application structure. User Interface: Role, Requirements, Problems Design patterns: Model – View – Controller, Observer/Observable.
Observer / Observable COMP 401 Fall 2014 Lecture 14 10/7/2014.
Chapter 7 Classes and Methods III: Static Methods and Variables Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition)
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
Sep 181 Example Program DemoTranslateEnglishGUI.java.
MIT AITI 2004 Swing Event Model Lecture 17. The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the.
Java for android Development Nasrullah Khan. Using instanceof in Android Development the classes such as Button, TextView, and CheckBox, which represent.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Java Events. Java Events Important definitions Overridden method Class vs. abstract class vs. interface Event Handling Definition Main components Windows.
Java Primer 1: Types, Classes and Operators
GoF Design Patterns (Ch. 26). GoF Design Patterns Adapter Factory Singleton Strategy Composite Façade Observer (Publish-Subscribe)
Introduction to Behavioral Patterns (1)
GoF Design Patterns (Ch. 26)
Java Programming Language
CMSC 202 Exceptions.
Presentation transcript:

Copyright W. Howden1 Lecture 14: Callbacks, Singletons and Wrappers

Copyright W. Howden2 Callback Pattern Context: controlling entity A calls/uses controlled entity B Problem: –B can have no control over A –How can B initiate something that is under the control of A without taking control of A? Solution: A gives B a pointer to one of its functions to call, or an object to “execute”, when the situation occurs

Copyright W. Howden3 Callback Objects Controller A will call a method B.b(a) in controllee B with an object a a must have an expected method a.callback() that is known to B and which will be called by B when the callback situation arises A must know the name of the method B.b() in B to call

Copyright W. Howden4 Callbacks and MV Separation Model View separation architecture(discussed in architecture lecture) –separation facilitates change of “look and feel” where Model is retained but View changed –controller is view, controllee is model –view posts callback object with model by calling appropriate method in model –callback object must have expected callback method

Copyright W. Howden5 DS Callback Example Frequent Datee Feature –normally GUI will call getADate() in DL when user indicates this user option –getADate() will return date information which GUI will display –if the found date has been dated many times, we want DL to display a GUI message (i.e. execute something in the GUI) –GUI registers a FrequentDatee call back object w

Copyright W. Howden6

7 Event Delegation and Callbacks Components and events, e.g. button b Options i)if b is pushed, b’s special response method is called ii)other code tells b what to do when button is pushed. “Register” a callback (actionListener) object x with b by executing b.addActionListener(x) - Callback pattern? sort of

Copyright W. Howden8 Related Patterns Can be used for CallBack –Publisher/Subscriber General pattern –Observer/Observable Supported by classes in Java library

Copyright W. Howden9 Publisher-Subscriber Special Event Manager object Objects interested in an event, register with event manager Objects who recognize event, publish occurrence of event with event manager Event manager informs subscribers –Expected to have a specific method that will be called

Copyright W. Howden10 Observer/Observable Observers register with Observable Observable recognizes event and calls specified method in observer Java Observer –Interface class, implemented by observers Java Observable –Class, extended by callback caller classes

Copyright W. Howden11 Java Observer Class Implementers must have an update() method which the Observable object x will call –update(Observable x, Object y) When Observable object x calls the update() method for a registered observer, it passes itself as an identifier and also a data object y

Copyright W. Howden12 Java Observable Class Users of this class extend it Inherited methods from Observable –addObserver(Observer z) Adds the object z to the observable’s list of observers –notifyObserver(Object y) Calls the update() method for each of the observers in its list of observers, passing y as the data object

Copyright W. Howden13 Singleton Pattern Context: class for which we only want a single instance, and to which we may want global access Solution: –reference the object globally through its class definition –class variable called “instance” whose value is an instance of the object –static method called instance() that Creates an instance if not created yet Returns the instance of the class

Copyright W. Howden14 DS Singleton Example Want to have a globally accessible object that records session history statistics Gets updated from different places, e.g. when different kinds of messages are generated Use the singleton pattern with a History class

Copyright W. Howden15 DS Singleton History Class

Copyright W. Howden16 Wrappers Take an existing entity and alter its behavior or interface by “embedding” it inside a class Types of wrappers –Adapter: emphasis is on altering interface, but could add some additional responsibilities responsibilities/behavior –Decorator: alters behavior or responsibilities but not interface –Combined

Copyright W. Howden17 Adapter Strategies Inheritance –Adaptor class implements the required new interface –Adaptor extends the adaptee, with new methods for performing the adaptee responsibilities, which conform to the new interface Composition –Adaptor class implements the required new interface –Adaptor’s constructor takes an adaptee object as an argument –Adaptor methods reference the adaptee object via its adaptee class methods

Copyright W. Howden18 Adapter - Inheritance

Copyright W. Howden19 Adaptor - Composition

Copyright W. Howden20 Adaptor Example – Primitive Data Reification Objectification of primitive data types in Java, i.e. wrap an instance in a class Why? When primitive is used as a parameter, it will be passed as call by value. –Cannot change its value inside the method May want to add to functionality, –e.g. Int is the objectification for int –Int.parseInt(String s) will return the int for s.

Copyright W. Howden21 User Defined Reification Example Interface BoolRefInterface { set(boolean b); boolean get() } Adaptee - boolean value Adaptor class BooleanRef implements BoolRefInterface {public boolean val; public BooleanRef(boolean x){this.val = x} public set(boolean b) {this.val = b;} public get() {return this.val;} }

Copyright W. Howden22 Adaptor Example – Interface Adaptors In order to carry out certain operations, a class may be required to implement a special interface Interface may contain many functions only a few of which are normally relevant Tedious to continually supply null definitions for the unneeded functions

Copyright W. Howden23 Interface Adaptor Strategy Construct a utility class that implements the interface and supplies null definitions for all the methods User extends the utility adaptor class instead of implementing the interface User supplies definitions for the methods of interest

Copyright W. Howden24 Java Interface Adaptor Example WindowListener interface –implemented by any object that wants to register itself as a listener for events generated by a Window – 7 methods in interface –window closing event that occurs when user clicks x in upper right corner requires definition for windowClosing() method only WindowAdaptor implements interface with 7 null functions –extend WindowAdapter and override windowClosing()

Copyright W. Howden25 Decorator Strategy Decorator wrapper- emphasis: – Goal is to alter the run time behavior of an object –Wrapper should preserve the interface Possible adaptor class approach: –adaptor sublcasses adaptee so has same interface –adaptor constructor takes wrappee as an argument, so it is altering it at runtime

Copyright W. Howden26 Decorator Class Diagram

Copyright W. Howden27 Decorator example - DS DateRequest objects x will look for a date when x.execute() is performed Want to add a special capability so that if Pamela is logged on, she always gets Dave, who is described using her desired props Solution: “decorate” DateRequest with a new DecoratedDateRequest class

Copyright W. Howden28 Decorator Pattern Variation DecoratedDateRequest interface –DecoratedDateRequest does not subclass DateRequest by has the same interface DecoratedDateRequest constructor –instead of taking a DateRequest object as a constructor parameter, it takes the constructor parameters for DateRequest, and uses them to build a DateRequest object if it needs it

Copyright W. Howden29 class DateRequest { String requester; DaterPreferences desiredProperties; public DateRequest(String name, DaterPreferences daterPreferences) {requester = name; desiredProperties = daterPreferences; } public MemberData execute() {MemberData memberData; memberData = dataBase.selectMember(desiredProperties); if (!(memberData == null)) { int dateeCount = ++memberData.adminData.timesDated; if (dateeCount > frequentDaterThreshold) {callBack.execute(); } String name = memberData.name; dataBase.updateField(name, "DateeCount", String.valueOf(dateeCount)); return memberData; } return(null); }

Copyright W. Howden30 class DecoratedDateRequest { String requester; DaterPreferences desiredProperties; public DecoratedDateRequest(String name, DaterPreferences daterPreferences) { requester = name; desiredProperties = daterPreferences; } public MemberData execute() { if (requester.equals("Pamela")) { MemberData memberData = new MemberData(); DateeData dateeData = new DateeData(); memberData.name = "Dave"; memberData.dateeData.occupation = "Programmer"; memberData.dateeData.religion = desiredProperties.religion; memberData.dateeData.gender = desiredProperties.gender; memberData.dateeData. = memberData.adminData.timesDated =12; return memberData; } else { return(new DateRequest(requester, desiredProperties).execute()); }

Copyright W. Howden31 Decorator Example – Java Stream Wrapper FileInputStream has a simple read() operation that reads a single byte Very inefficient, would like to buffer the input Solution: “decorate” FileInputStream with a decorator class BufferedInputStream

Copyright W. Howden32 Decorator Pattern Variation BufferedInputStream interface –has the same interface as FileInputStream, but it is not a subclass BufferedInputStream constructor –does follow the pattern, its constructor can take a FileInputStream object as an argument, but actual constructor argument type is more general

Copyright W. Howden33 FileInputStream and BufferedInputStream