Observer Pattern Context:

Slides:



Advertisements
Similar presentations
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)
Advertisements

Event-Driven Programming Thus far, our programs have been executed one statement after the other However, many programs depend on user actions to dictate.
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.
JFC/Swing lectures O BSERVER PATTERN – general form Idea: decouple event from event handling Concrete Observable Abstract Observable Concrete Observer.
Java GUI Libraries Swing Programming. Swing Components Swing is a collection of libraries that contains primitive widgets or controls used for designing.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Winter 2007ACS-3913 Ron McFadyen1 Observer Pattern Problem: There are many objects (observers / subscribers) needing to know of the state changes, or events,
Graphical User Interfaces
Object-Oriented Analysis and Design
1 Object Oriented Design & Patterns Part 1. 2 Design Patterns Derived from architectural patterns: –rules for design of buildings –describe common problems,
Graphics without NGP The key to effectively using graphics in Java is understanding: –the basic components of the graphics library –the patterns that are.
Io package as Java’s basic I/O system continue’d.
Design Patterns and Graphical User Interfaces Horstmann ,
Observer Design Pattern Source: Design Patterns – Elements of Reusable Object- Oriented Software; Gamma, et. al.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
CSC 313 – Advanced Programming Topics. Observer Pattern Intent  Efficiently perform 1-to-many communication  Easy to respond dynamically when event(s)
Java Swing, Events and MVC Optional Readings: Eckel’s Thinking in Java: Chap 14 (
MIT AITI 2003 Lecture 17. Swing - Part II. The Java Event Model Up until now, we have focused on GUI's to present information (with one exception) Up.
CS 210 Introduction to Design Patterns September 7 th, 2006.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
Chapter 19 Designing the GUI front-end: the Model-View-Controller pattern.
Java Event Handling CSIS 3701: Advanced Object Oriented Programming.
CS 350 – Software Design The Observer Pattern – Chapter 18 Let’s expand the case study to include new features: Sending a welcome letter to new customers.
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
GUIs for Video Games. The Plan ● Layout suggestions ● Observer/Observable ● Steps to writing Observer/Observables ● Sample Code ● Practice.
Chapter 12 1 TOPIC 13B l Buttons and Action Listeners Window Interfaces Using Swing Objects.
 2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(1/15) MVC and Swing Joel Adams and Jeremy Frens Calvin College.
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.
CSC 313 – Advanced Programming Topics. Observer Pattern in Java  Java ♥ Observer Pattern & uses everywhere  Find pattern in JButton & ActionListener.
CS-1020 Dr. Mark L. Hornick 1 Event-Driven Programming.
CSC 480 Software Engineering Design With Patterns.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 27 JavaBeans and.
OBSERVER DESIGN PATTERN. Behavioral Patterns  Behavioral patterns are those patterns that are most specifically concerned with communication between.
(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.
Graphical User Interfaces A Graphical User Interface (GUI) in Java is created with at least three kinds of objects: –components, events, and listeners.
The Observer Pattern.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 32 JavaBeans and Bean.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
Event-Driven Programming F Procedural programming is executed in procedural order. F In event-driven programming, code is executed upon activation of events.
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.
The Observer Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
Observer / Observable COMP 401 Fall 2014 Lecture 14 10/7/2014.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Lesson 28: More on the GUI button, frame and actions.
Observer Pattern Keeping An Eye on Things Need to introduce observer pattern formally first, include book definition & design principle Keeping An Eye.
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.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Chapter 32 JavaBeans and Bean Events
Graphical User Interfaces
Behavioral Patterns Algorithms and the assignment of responsibilities among objects Describe not just patterns of objects or classes but also the patterns.
Sections Inheritance and Abstract Classes
Chapter 36 JavaBeans and Bean Events
Web Design & Development Lecture 11
Observer Design Pattern
Architectural Patterns for Interactive Software
MVC Paradigm The MVC paradigm breaks applications or interfaces into three parts: the model, the view, and the controller. A --> 25 % B --> 60 % C -->
GUI Programming III: Events
Design Patterns in Swing and AWT
Doug Jeffries CS490 Design Patterns May 1, 2003
Designing with Interfaces
Introduction to Event Handling
Model-View-Controller (MVC) Pattern
CSC 480 Software Engineering
Constructors, GUI’s(Using Swing) and ActionListner
Advanced ProgramMING Practices
Advanced ProgramMING Practices
Using threads for long running tasks.
CSC 480 Software Engineering
Presentation transcript:

Observer Pattern Context: 08/15/09 Observer Pattern Context: One object (the Subject) is the source of events. Other objects (Observers) want to know when an event occurs. Or: several objects should be immediately updated when the state of one object changes, e.g. an editor with live preview.. Forces: We don't want the observers to poll for changes, which is inefficient. We don't want to complicate the Subject with a lot of code for event notification. (Not its purpose!)

Observer Pattern Solution: 08/15/09 Observer Pattern Solution: (1) Subject provides a method for Observer to register itself as wanting to receive event notification. (2) Subject calls a method when observers should be notified. (3) To avoid complicating the subject, implement the registration and event notification code in a separate class. This can be a superclass of the Subject, or another class that the Subject uses (delegate to it).

UML for Observer Pattern 08/15/09 UML for Observer Pattern (1) Subject provides a method for Observers to register themselves as wanting to be notified of events. Method: addObserver( ) (2) Each Observer implements a known method (notify) for the Subject to invoke when an event occurs. Subject - observers: Collection +addObserver( Observer ) +removeObserver( ... ) Observer +notify( event: Object ) ... ConcreteObserver +notify( event ) ... AnotheObserver +notify( event ) ... What are some examples of the Observer Pattern?

JButton uses Observer Subject: JButton is the source of events. 08/15/09 JButton uses Observer Subject: JButton is the source of events. Event: button press (an ActionEvent) Observer: any object that want to know when the button is pressed. How to implement: 1. Observer implements ActionListener, and defines an actionPerformed( ) method. 2. Observer registers itself by calling button.addActionListener( )

JButton Observers This observer counts button presses. 08/15/09 JButton Observers This observer counts button presses. /** An observer that counts button presses */ public class ClickCounter implements ActionListener { private int count = 0; /** The event notification method. */ public void actionPerformed(ActionEvent evt) { count += 1; System.out.println("Click number "+count); } public int getClickCount() { return count; }

08/15/09 Register the Observer We must add ClickCounter as an observer of the JButton. This is called registering an observer. JButton button = new JButton("Press Me"); frame.add(button); ClickCounter counter = new ClickCounter(); // register the observer button.addActionListener( counter );

Benefits of using Observers 08/15/09 Benefits of using Observers 1. JButton is not coupled to the actual observer classes. JButton depends only on the interface for observers. 2. We can define and add new observers any time (extensible). 3. We can reuse the same observer for many components.

Table for Identifying a Pattern 08/15/09 Table for Identifying a Pattern Name In Pattern Name in Application: this is for a JButton Subject JButton Observer ActionListener Concrete Observer a class that implements ActionListener addObserver( Observer ) addActionListener( ) notify( Event ) [in the observer] actionPerformed( ActionEvent ) notifyObservers [in Subject] fireActionPerformed( )

Adding Observers to your App 08/15/09 Adding Observers to your App How can we apply the Observer Pattern to our code? Example: A UI for coin purse that tells us what the balance is.

Observer Pattern in Java 08/15/09 Observer Pattern in Java Java provides an Observable class and Observer interface that make it easy to use the Observer pattern.. Observable - observers: Collection +addObserver( Observer ) +deleteObserver( ... ) +notifyObservers( Object ) Observer +update( Observable, Object ) addObserver(this) YourApplication -event( ) ... YourObserver +update( observable, event ) ... void event( ) { setChanged( ); notifyObservers(obj);

Using the Observable class 08/15/09 Using the Observable class (1) Declare that your Subject class extends Observable public class MySubject extends Observable { /** An event the observers want to know about */ public void somethingHappened( ) { doSomeWork( ); // now notify the observers setChanged( ); notifyObservers( ); // can include a parameter } (2) When an event or change occurs, invoke setChanged() and notifyObservers()

08/15/09 Writing an Observer (3) Declare that observers implement the Observer interface. public class MyObserver implements Observer { /* This method receives notification from the * subject (Observable) when something happens * @param subject Observable that caused notif. * @param message is value of parameter sent * by subject. May be null. */ public void update( Observable subject, Object message ) { mySubject = (MySubject)subject; ... } (4) update takes action using notification from the Subject.

Last Step: add Observers to Subject 08/15/09 Last Step: add Observers to Subject Call addObserver( ) to register the Observers with subject. public static void main(String [] args) { Observable subject = new MySubject( ); MyObserver observer = new MyObserver( ); subject.addObserver( observer ); subject.run( ); }

What are the interesting events? 08/15/09 Example for Coin Purse What are the interesting events? GUI observers Observable notifyObservers() extends Purse insert( Money ) withdraw( amt )

Purse with observer notification 08/15/09 Purse with observer notification The purse should notify observers when the state of the purse changes. Draw a sequence diagram of what happens, using insert() as example.

C# Delegates as Observers 08/15/09 C# Delegates as Observers Delegate is a type in the C# type system. It describes a group of functions with same parameters. Delegate can act as a collection for observers. /** define a delegate that accepts a string **/ public delegate void WriteTo( string msg ); /** create some delegates **/ WriteTo observers = new WriteTo( out.WriteLine ); observers += new WriteTo( button.setText ); observers += new WriteTo( textarea.append ); /** call all the observers at once! **/ observers("Wake Up!");