CSE 331 Software Design & Implementation Dan Grossman Winter 2014 Events, Listeners, and Callbacks (Based on slides by Mike Ernst, David Notkin, Hal Perkins)

Slides:



Advertisements
Similar presentations
Chapter 16 Graphical User Interfaces
Advertisements

Chapter 16 Graphical User Interfaces John Keyser’s Modifications of Slides by Bjarne Stroustrup
The Model-View Approach in Java. OK, you’ve got “Hello World” running... What now?
Multi-threaded applications SE SE-2811 Dr. Mark L. Hornick 2 What SE1011 students are told… When the main() method is called, the instructions.
Observer Method 1. References Gamma Erich, Helm Richard, “Design Patterns: Elements of Reusable Object- Oriented Software” 2.
OOP Design Patterns Chapters Design Patterns The main idea behind design patterns is to extract the high level interactions between objects and.
The Bridge Pattern.. Intent Decouple an abstraction from its implementation so that the two can vary independently Also known as: Handle/Body.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Immutable Objects and Classes.
System Architecture Lecture 3 CSE 111 Spring /22/20151Copyright William E. Howden.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Threads II. Review A thread is a single flow of control through a program Java is multithreaded—several threads may be executing “simultaneously” If you.
CSE 331 Software Design & Implementation Dan Grossman Spring 2015 GUI Event-Driven Programming (Based on slides by Mike Ernst, Dan Grossman, David Notkin,
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Chapter 3 Introduction to Collections – Stacks Modified
Observer Design Pattern Source: Design Patterns – Elements of Reusable Object- Oriented Software; Gamma, et. al.
Software Construction Lecture 10 Frameworks
Implementing Design Patterns Using Java St. Louis Java Special Interest Group Eric M. Burke Object Computing, Inc. Presented on July 9, 1998 (updated July.
CSC 313 – Advanced Programming Topics. Observer Pattern Intent  Efficiently perform 1-to-many communication  Easy to respond dynamically when event(s)
Week 3, Day 1: Processes & Threads Return Quiz Processes Threads Lab: Quiz Lab 3: Strategy & Factory Patterns! SE-2811 Slide design: Dr. Mark L. Hornick.
Design Patterns Lecture III. What Is A Pattern? Current use comes from the work of the architect Christopher Alexander Alexander studied ways to improve.
CSE 331 SOFTWARE DESIGN & IMPLEMENTATION MODULAR DESIGN PRINCIPLES Autumn 2011 Google image search on “designing software modules”
Chapter 26 GoF Design Patterns. The Adapter Design Pattern.
CSC 313 – Advanced Programming Topics. Design Pattern Intent  Each design pattern is a tool  Like all tools, have reason for being.
Observer Behavioral Pattern. Intent Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified.
CSE 331 SOFTWARE DESIGN & IMPLEMENTATION MIDTERM REVIEW Autumn 2011.
Week 3, Day 1: Processes & Threads Processes Threads SE-2811 Slide design: Dr. Mark L. Hornick Content: Dr. Hornick Errors: Dr. Yoder 1.
3-1 State Design Pattern C Sc 335 Rick Mercer. State Design Pattern State is one of the Behavioral patterns It is similar to Strategy Allows an object.
Frameworks CompSci 230 S Software Construction.
CSC 313 – Advanced Programming Topics. Observer Pattern in Java  Java ♥ Observer Pattern & uses everywhere  Find pattern in JButton & ActionListener.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Event-Driven Programming 1.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 27 JavaBeans and.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
OBSERVER DESIGN PATTERN. Behavioral Patterns  Behavioral patterns are those patterns that are most specifically concerned with communication between.
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAMMING PRACTICES Model View.
(1) Introduction to Java GUIs Philip Johnson Collaborative Software Development Laboratory Information and Computer Sciences University of Hawaii Honolulu.
1 CSE 331 Model/View Separation and Observer Pattern slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia.
CSE 331 Software Design & Implementation Hal Perkins Winter 2013 Events, Listeners, and Callbacks (slides by Mike Ernst and David Notkin) 1.
The Observer Pattern.
CSE 331 Software Design & Implementation Dan Grossman Fall 2014 Abstraction Functions (Based on slides by Mike Ernst, David Notkin, Hal Perkins)
1 COS 260 DAY 12 Tony Gauvin. 2 Agenda Questions? 5 th Mini quiz –Chapter 5 40 min Assignment 3 Due Assignment 4 will be posted later (next week) –If.
L10: Model-View-Controller General application structure. User Interface: Role, Requirements, Problems Design patterns: Model – View – Controller, Observer/Observable.
The Observer Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
Observer / Observable COMP 401 Fall 2014 Lecture 14 10/7/2014.
Slide design: Dr. Mark L. Hornick
Observer Pattern Keeping An Eye on Things Need to introduce observer pattern formally first, include book definition & design principle Keeping An Eye.
Module dependences and decoupling CSE 331 University of Washington.
Observer Pattern Context:
SE-2811 Software Component Design
Creational Pattern: Prototype
CSE 331 Software Design & Implementation
Observer Design Pattern
Observer Design Pattern
CSE 331 Software Design and Implementation
CSE 331 Software Design and Implementation
Design Patterns, cont..
Introduction to Behavioral Patterns (1)
CSE 331 Software Design and Implementation
CSE 143 Lecture 2 Collections and ArrayIntList
CSE 331 Software Design & Implementation
Design pattern Lecture 9.
Advanced ProgramMING Practices
8. Observer Pattern SE2811 Software Component Design
9. Threads SE2811 Software Component Design
Advanced ProgramMING Practices
CSE 331 Software Design & Implementation
9. Threads SE2811 Software Component Design
CSE 331 Software Design & Implementation
Software Design Lecture : 40.
Software Design Lecture : 28.
Presentation transcript:

CSE 331 Software Design & Implementation Dan Grossman Winter 2014 Events, Listeners, and Callbacks (Based on slides by Mike Ernst, David Notkin, Hal Perkins)

The limits of scaling What prevents us from building huge, intricate structures that work perfectly and indefinitely? –No friction –No gravity –No wear-and-tear … it’s the difficulty of understanding them So we split designs into sensible parts and reduce interaction among the parts –More cohesion within parts –Less coupling across parts CSE331 Winter 20142

Design exercise #1 Write a typing-break reminder program Offer the hard-working user occasional reminders of the perils of Repetitive Strain Injury, and encourage the user to take a break from typing. Naive design: –Make a method to display messages and offer exercises –Make a loop to call that method from time to time (Let's ignore multi-threaded solutions for this discussion) 3CSE331 Winter 2014

TimeToStretch suggests exercises public class TimeToStretch { public void run() { System.out.println("Stop typing!"); suggestExercise(); } public void suggestExercise() { … } 4CSE331 Winter 2014

Timer calls run() periodically public class Timer { private TimeToStretch tts = new TimeToStretch(); public void start() { while (true) {... if (enoughTimeHasPassed) { tts.run(); }... } 5CSE331 Winter 2014

Main class puts it together class Main { public static void main(String[] args) { Timer t = new Timer(); t.start(); } This program, as designed, will work... But we can do better 6CSE331 Winter 2014

Module dependency diagram (MDD) An arrow in a module dependency diagram (MDD) indicates “depends on” or “knows about” –Simplistically: “any name mentioned in the source code” What’s wrong with this diagram? –Does Timer really need to depend on TimeToStretch ? –Is Timer re-usable in a new context? 7 TimeToStretch Timer Main Timer depends on TimeToStretch Main depends on Timer CSE331 Winter 2014

Decoupling Timer needs to call the run method –Timer does not need to know what the run method does Weaken the dependency of Timer on TimeToStretch –Introduce a weaker specification, in the form of an interface or abstract class public abstract class TimerTask { public abstract void run(); } Timer only needs to know that something (e.g., TimeToStretch ) meets the TimerTask specification 8CSE331 Winter 2014

TimeToStretch (version 2) public class TimeToStretch extends TimerTask { public void run() { System.out.println("Stop typing!"); suggestExercise(); } public void suggestExercise() {... } 9CSE331 Winter 2014

Timer (version 2) public class Timer { private TimerTask task; public Timer(TimerTask task) { this.task = task; } public void start() { while (true) {... task.run(); } Main creates a TimeToStretch object and passes it to Timer : Timer t = new Timer(new TimeToStretch()); t.start(); 10CSE331 Winter 2014

Module dependency diagram (version 2) Timer depends on TimerTask, not TimeToStretch –Unaffected by implementation details of TimeToStretch –Now Timer is much easier to reuse –Main depends on the constructor for TimeToStretch Main still depends on Timer (is this necessary?) TimeToStretch Timer Main TimerTask Subclassing Dependence 11CSE331 Winter 2014

The callback design pattern TimeToStretch creates a Timer, and passes in a reference to itself so the Timer can call it back –This is a callback – a method call from a module to a client that it notifies about some condition Use a callback to invert a dependency –Inverted dependency: TimeToStretch depends on Timer (not vice versa) Less obvious coding style, but more “natural” dependency –Side benefit: Main does not depend on Timer 12CSE331 Winter 2014

Callbacks Callback: “Code” provided by client to be used by library In Java, pass an object with the “code” in a method Synchronous callbacks: Examples: HashMap calls its client’s hashCode, equals Useful when library needs the callback result immediately Asynchronous callbacks: Examples: GUI listeners Register to indicate interest and where to call back Useful when the callback should be performed later, when some interesting event occurs 13CSE331 Winter 2014

TimeToStretch (version 3) public class TimeToStretch extends TimerTask { private Timer timer; public TimeToStretch() { timer = new Timer(this); } public void start() { timer.start(); } public void run() { System.out.println("Stop typing!"); suggestExercise(); }... } Register interest with the timer Callback entry point 14CSE331 Winter 2014

Main (version 3) TimeToStretch tts = new TimeToStretch(); tts.start(); –Uses a callback in TimeToStretch to invert a dependency –This MDD shows the inversion of the dependency between Timer and TimeToStretch (compare to version 1) TimeToStretch Timer Main TimerTask Main does not depend on Timer TimeToStretch depends on Timer 15CSE331 Winter 2014

Decoupling and design A good design has dependences (coupling) only where it makes sense While you design (before you code), examine dependences Don’t introduce unnecessary coupling Coupling is an easy temptation if you code first –Suppose a method needs information from another object: –If you hack in a way to get it: The hack might be easy to write It will damage the code’s modularity and reusability More complex code is harder to understand 16CSE331 Winter 2014

Design exercise #2 A program to display information about stocks –Stock tickers –Spreadsheets –Graphs Naive design: –Make a class to represent stock information –That class updates all views of that information (tickers, graphs, etc.) when it changes 17CSE331 Winter 2014

Main class gathers information and stores in Stocks Stocks class updates viewers when necessary Problem: To add/change a viewer, must change Stocks Better: insulate Stocks from the vagaries of the viewers Stocks StockGraph StockTicker Spreadsheet Main Module dependency diagram 18CSE331 Winter 2014

Weaken the coupling What should Stocks class know about viewers? –Only needs an update method to call with changed data –Old way: void updateViewers() { ticker.update(newPrice); spreadsheet.update(newPrice); graph.update(newPrice); // Edit this method to // add a new viewer.  } CSE331 Winter

Weaken the coupling What should Stocks class know about viewers? –Only needs an update method to call with changed data –New way: The “observer pattern” CSE331 Winter interface PriceObserver { void update(PriceInfo pi); } class Stocks { private List observers; void addObserver(PriceObserver pi) { observers.add(pi); } void notifyObserver(PriceInfo i) { for (PriceObserver obs : observers) obs.update(i); } … } Do the callbacks Register a callback

update Create (or be) observers Create Stocks and add observers The observer pattern Stocks not responsible for viewer creation Main passes viewers to Stocks as observers Stocks keeps list of PriceObservers, notifies them of changes Issue: update method must pass enough information to (unknown) viewers Stocks StockGraph Spreadsheet Main StockTicker PriceObserver Create viewers and get observers 21CSE331 Winter 2014

A different design: pull versus push The Observer pattern implements push functionality A pull model: give viewers access to Stocks, let them extract the data they need “Push” versus “pull” efficiency can depend on frequency of operations (Also possible to use both patterns simultaneously.) Stocks StockGraph Spreadsheet Main Stocks.new StockTicker new(Stocks) 22CSE331 Winter 2014

Another example of Observer pattern // Represents a sign-up sheet of students public class SignupSheet extends Observable { private List students = new ArrayList (); public void addStudent(String student) { students.add(student); setChanged(); notifyObservers(); } public int size() { return students.size(); } … } Part of the JDK 23CSE331 Winter 2014 SignupSheet inherits many methods including: void addObserver(Observer o) protected void setChanged() void notifyObservers()

An Observer public class SignupObserver implements Observer { // called whenever observed object changes // and observers are notified public void update(Observable o, Object arg) { System.out.println("Signup count: " + ((SignupSheet)o).size());‏ } Part of the JDK Not relevant to us cast because Observable is non-generic  24CSE331 Winter 2014

Registering an observer SignupSheet s = new SignupSheet(); s.addStudent("billg"); // nothing visible happens s.addObserver(new SignupObserver()); s.addStudent("torvalds"); // now text appears: "Signup count: 2" Java's “Listeners” (particularly in GUI classes) are examples of the Observer pattern (Feel free to use the Java observer classes in your designs – if they are a good fit – but you don’t have to use them) 25CSE331 Winter 2014

User interfaces: appearance vs. content It is easy to tangle up appearance and content –Particularly when supporting direct manipulation (e.g., dragging line endpoints in a drawing program) –Another example: program state stored in widgets in dialog boxes Neither can be understood easily or changed easily This destroys modularity and reusability –Over time, it leads to bizarre hacks and huge complexity –Code must be discarded Callbacks, listeners, and other patterns can help 26CSE331 Winter 2014