Event-driven design will set you free The Observer Pattern 1.

Slides:



Advertisements
Similar presentations
Android Application Development Tutorial. Topics Lecture 4 Overview Overview of Sensors Programming Tutorial 1: Tracking location with GPS and Google.
Advertisements

Copyright © 2012 Pearson Education, Inc. Chapter 9 Delegates and Events.
Winter 2007ACS-3913 Ron McFadyen1 Also known as publish/subscribe The essence of this pattern is that one or more objects (called observers or listeners)
Chapter 2: The Observer Pattern. Consider the Following Application Application specification Humidity Temperature Pressure Weather Station Weather Data.
March Ron McFadyen1 Design Patterns In software engineering, a design pattern is a generally repeatable solution to a commonly-occurring problem.
Event Driven Programming and GUIs Part 3 CS221 – 4/15/09.
Spring 2010ACS-3913 Ron McFadyen1 Weather Station Page 39+ In this application, weather station devices supply data to a weather data object. As the data.
March Ron McFadyen1 Design Patterns In software engineering, a design pattern is a generally repeatable solution to a commonly-occurring problem.
Winter 2007ACS-3913 Ron McFadyen1 Observer Pattern Problem: There are many objects (observers / subscribers) needing to know of the state changes, or events,
Object-Oriented Analysis and Design
Introduction to AppInventor Dr. José M. Reyes Álamo.
Chapter 6: Graphical User Interface (GUI) and Object-Oriented Design (OOD) J ava P rogramming: Program Design Including Data Structures Program Design.
® IBM Software Group © 2006 IBM Corporation JSF Tab Controls This Learning Module shows how to develop server-side EGL applications with dynamic content.
Android Sensors & Async Callbacks Jules White Bradley Dept. of Electrical and Computer Engineering Virginia Tech
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Welcome to CIS 083 ! Events CIS 068.
Tip Calculator App Building an Android App with Java © by Pearson Education, Inc. All Rights Reserved.
Rajab Davudov. Agenda Eclipse, ADT and Android SDK APK file Fundamentals – Activity – Service – Content Provider – Broadcast Receiver – Intent Hello World.
16 Services and Broadcast Receivers CSNB544 Mobile Application Development Thanks to Utexas Austin.
Android Accessing GPS Ken Nguyen Clayton State University 2012.
CSC 313 – Advanced Programming Topics. Observer Pattern Intent  Efficiently perform 1-to-many communication  Easy to respond dynamically when event(s)
Java Programming: From Problem Analysis to Program Design, Second Edition1  Learn about basic GUI components.  Explore how the GUI components JFrame,
Putting together a complete system Chapter 10. Overview  Design a modest but complete system  A collection of objects work together to solve a problem.
ISP666 MVC & Design Patterns. Outline Review Event Programming Model Model-View-Controller Revisit Simple Calculator Break Design Patterns Exercise.
CS 210 Introduction to Design Patterns September 7 th, 2006.
Observer Behavioral Pattern. Intent Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified.
Programming in C# Observer Design Pattern
Session 11 Border Layout, using Panels, Introduction to PinBallGame.
1 Web Based Programming Section 8 James King 12 August 2003.
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
CSC 205 – Java Programming II Applet. Types of Java Programs Applets Applications Console applications Graphics applications Applications are stand-alone.
Model View Controller A Pattern that Many People Think They Understand, But Has A Couple Meanings.
Game Programming Patterns Event Queue From the book by Robert Nystrom
“The perfect project plan is possible if one first documents a list of all the unknowns.” Bill Langley.
Object Oriented Software Development
Java Applets: GUI Components, Events, Etc. Ralph Westfall June, 2010.
Location. GPS Global Positioning System – At least 4 satellites typically used 3 required extra for error detection and altitude typically accurate within.
Observer Please Snarf the Code for Today’s Class..
Observer, Strategy, Decorator, Prototype,. Observer Pattern Dependence mechanism / publish-subscribe / event handler / constraints / broadcast Let objects.
Design Patterns. OO-Concepts Don’t rewrite code Encapsulation Inheritance Write flexible code.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
Design Patterns David Talby. This Lecture Re-routing method calls Chain of Responsibility Coding partial algorithms Template Method The Singleton Pattern.
Event-driven design will set you free The Observer Pattern 1.
Testing OO software. State Based Testing State machine: implementation-independent specification (model) of the dynamic behaviour of the system State:
MOBILE COMPUTING D10K-7D02 MC05: Android UI Design Dr. Setiawan Hadi, M.Sc.CS. Program Studi S-1 Teknik Informatika FMIPA Universitas Padjadjaran.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
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.
CHAPTER 14 Classes, Objects, and Games XNA Game Studio 4.0.
(c) University of Washington02-1 CSC 143 Java Object and Class Relationships: Interfaces Reading: Ch. 9 (on Java interfaces)
OOD teaches a complicated method, best for large systems. Here we teach the ten cent version. OO Design for the Rest of Us 1.
The Observer Pattern.
Creating a GUI Class An example of class design using inheritance and interfaces.
Sensors – Part 2 SE 395/595. Location in Android LocationManager class – Configure providers and their listeners LocationListener class – Handles update.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 15 Event-Driven Programming and.
Slide design: Dr. Mark L. Hornick
My Observer Goes to 11 Model-View Controller 1. Which is the best class diagram? 2 ___Edge___ drop() _Vertex_ addEdge() dropEdge() _Iterable_ * 2 ___Edge___.
Part 2: Interactivity. In this section Using the laptop’s inputs Adding game controllers and MIDI controllers Interacting with controllers, other software,
Java for android Development Nasrullah Khan. Using instanceof in Android Development the classes such as Button, TextView, and CheckBox, which represent.
How to develop a VoIP softphone in C# by using OZEKI VoIP SIP SDK This presentation demonstrates the first steps concerning to how to develop a fully-functional.
Observer Pattern Context:
Design Patterns Source: “Design Patterns”, Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides And Created.
Slide design: Dr. Mark L. Hornick
Android – Event Handling
Observer Design Pattern
Sensors, maps and fragments:
EE 422C Java FX.
Introduction to Behavioral Patterns (1)
8. Observer Pattern SE2811 Software Component Design
Border Layout, using Panels, Introduction to PinBallGame
Presentation transcript:

Event-driven design will set you free The Observer Pattern 1

BDD-style Testing This is feature testing, not unit testing (yes, you have to do it this way on the project) 2

Example: Game of Life  Asides:  Gives actual inputs and outputs  Progressive when-then clauses  Follow BDD scenario’s structure and content when forming a testcase  Each “Given”, “When”, and “Then” will have its own method  Given: initialization  When: action to be tested (do the action)  Then: check that action made intended change  Make the test sound like the scenario 3

Example: Game of Life, II // Given a $width by $height game void gameIsRunning (int width, int height) { game = new Game(width, height); renderer = new StringRenderer(); game.registerObserver(renderer); } // When I toggle the cell at ($column, $row); void iToggleTheCellAt (int column, int row) { game.toggleCellAt(column, row); } // Then the grid should look like $grid void theGridShouldLookLike (String grid) { assertThat(renderer.asString(), equalTo(grid)); } 4 Scenario 1: …

Example: Game of Life, public class TestGameOfLifeScenario1 { Game public static void GivenA5by5Game() { gameIsRunning (5, 5); public void A_WhenIToggleTheCellAt2comma3() { iToggleTheCellAt (2, 3); theGridShouldLookLike (“…”); public void B_WhenIToggleTheCellAt2comma4() { iToggleTheCellAt (2, 4); theGridShouldLookLike (“…”); public void C_WhenIToggleTheCellAt2comma3() { iToggleTheCellAt (2, 3); theGridShouldLookLike (“…”); } }  I’ve asserted an alphabetic ordering of the tests (and named them thusly) so that the progression holds up  Note how the test cases look and sound like the scenario  More test cases can be written with same base methods  True BDD writes test cases before the code. (I don’t.) 5 Scenario 1: …

Observer pattern Event-driven programming, call-backs, listening, and all that 6

Event-Driven Software Rules  What’s an event?  It’s a kind of broadcast message that can be “heard” by any object that chooses to listen  A typical event message from an object is “I changed!”  This enables objects who depend on that object to update themselves  E.g., update the map’s center when location changes; GPS’s event message is, in essence, “I changed!”  Android depends heavily on events  Every sensor on phone sends events  Like above: GPS periodically “announces” changes in location  User interfaces run almost entirely on events  Every mouse motion, click, etc.,  But wait a second, Java doesn’t have events! 7

Simulating Events with Callbacks  Classic software technique (OS, games, OOD)  If the map control wants to receive events from location manager, it “registers” with it  conceptually: locationMgr.register(mapControl)  Later, when location changes, locationMgr “calls back” mapControl (and all others who registered):  conceptually (in locationMgr): foreach (LocListener L : Listeners) { L.changed(this); }  This is how we implement events with methods  Note: many details omitted, but forthcoming 8

Actual Example Android Code (yuck!) // Acquire reference to the Location Manager LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); // Create a callback that handles location updates LocationListener locationListener = new LocationListener() { public void onLocationChanged (Location location) { // Called when a new location is found by the network location provider. makeUseOfNewLocation(location); } … }; // Register the callback with Location Manager to receive location updates locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, locationListener ); 9 Just the registration part

Why go to all this trouble? Knows About  We say component A knows about component B if A references an interface defined by B  In example below, WeatherData knows about Weather Station and Display One, Two, & Three 10

What’s wrong with this design? 11 Because WeatherData knows about each individual display, adding a display means that WeatherData has to be updated. Unfortunately, we anticipate adding more displays (e.g., more users)

We have a knows-about problem  Because WeatherData knows about the individual displays, adding a new display requires changing WeatherData as well  Violates our design goal of localizing change  (Adding features shouldn’t affect internals of a class.) 12

WeatherData needs a way to yell, and others to hear  It’s design patterns, it’s gotta involve interfaces  But have to handle 0, 1, 2, 3… displays 13 Hey, these all kind of have the same interface!

Loop over interface’d objects 14 for (weatherUpdateInterface : weatherUpdateInterfaces) weatherUpdateInterface.update(temp, humidity, pressure);  Now fully dynamic – can add and delete any time, as many or few as we want  But how does WeatherData get access to the weatherUpdateInterface objects to call?

Three interfaces (first two in the pattern) 15 Since update() is kind of specific, I’d call this WeatherObserver Interface for the thing being observed Not part of pattern, don’t really need it

Refactored Design 16 also to call removeObserver

Class Diagram View 17

Coupling in Observer  Coupling is the property that when one thing changes, another thing may have to change (they are coupled)  Want loosely coupled designs 18  Note that Observer is “coupled” to weather generically, and hence to WeatherData generally  But the designer of WeatherData chose the Observer interface  ForecastDisplay can’t be implemented until Observer has been worked out  We have another pattern later that lets ForecastDisplay be preexisting  Critical for using existing dials, etc.

Actual Example Android Code (yuck!) // Acquire reference to the Location Manager LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); // Create a listener that handles location updates LocationListener locationListener = new LocationListener () { public void onLocationChanged (Location location) { // Called when a new location is found by the network location provider. makeUseOfNewLocation(location); } public void onStatusChanged (String provider, int status, Bundle extras) {} public void onProviderEnabled (String provider) {} public void onProviderDisabled (String provider) {} }; // Register the listener with the Location Manager to receive location updates locationManager. requestLocationUpdates ( LocationManager.NETWORK_PROVIDER, 0, 0, locationListener ); 19 Just the registration part make an object instance of class anonymous class declaration of type LocationListener interface

Android Loc Listener Class Diagram 20 > ___LocationListener___ onStatusChanged(…) onProviderEnabled(…) onProviderDisabled(…) ____ _____ onStatusChanged(…) onProviderEnabled(…) onProviderDisabled(…) _____LocationManager_____ LocationListener Ls__________ requestLocationUpdates(…) … Breaks the pattern on the subject side There’s no Subject interface implemented by LocManager Makes building new location subjects harder But Android really only needs one, so why bother? (tradeoffs) Also, concrete LocListener doesn’t have ref to subject to unregister Looks like creator of concrete LocListener has that reference Breaks the pattern on the subject side There’s no Subject interface implemented by LocManager Makes building new location subjects harder But Android really only needs one, so why bother? (tradeoffs) Also, concrete LocListener doesn’t have ref to subject to unregister Looks like creator of concrete LocListener has that reference

Android also lets you do it HFDP way 21 public class MainActivity extends Activity implements LocationListener { public void onLocationChanged (Location location) { // Called when new location is found by network location provider. makeUseOfNewLocation(location); } public void onStatusChanged (String provider, int status, Bundle extras) {} public void onProviderEnabled (String provider) {} public void onProviderDisabled (String provider) {} … Now the concrete LocationListener has a name Now it’s the “outer” class that is LocationListener Means it has reference to LocationManager to unregister itself Still no Subject interface implemented by LocationManager Now the concrete LocationListener has a name Now it’s the “outer” class that is LocationListener Means it has reference to LocationManager to unregister itself Still no Subject interface implemented by LocationManager

Take-Aways  Revisited lessons:  Classes: bad; Interfaces: good  Program to interfaces, not implementations  Aggregate/compose, don’t subclass  New lessons:  Advanced communication concepts can be emulated (callbacks: events with methods)  Observer pattern is an elegant, reusable solution  Use of interfaces ensures that (changeable) concrete classes only refer to (stable) interfaces  Gets right “knows about” relationship  Localization of change (low coupling) 22