OBSERVER DESIGN PATTERN. Behavioral Patterns  Behavioral patterns are those patterns that are most specifically concerned with communication between.

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

Lecture 12 Observer Pattern UML Class Diagrams (repetition) Use Case Diagrams Sequence Diagrams Statechart Diagrams.
The Observer Pattern SE-2811 Dr. Mark L. Hornick 1.
Observer Method 1. References Gamma Erich, Helm Richard, “Design Patterns: Elements of Reusable Object- Oriented Software” 2.
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.
Reza Gorgan Mohammadi AmirKabir University of Technology, Department of Computer Engineering & Information Technology Advanced design.
Observer Pattern Fall 2005 OOPD John Anthony. What is a Pattern? “Each pattern describes a problem which occurs over and over again in our environment,
Observer Pattern Tu Nguyen. General Purpose When one object changes state, all the dependent objects are notified and updated. Allows for consistency.
BehavioralCmpE196G1 Behavioral Patterns Chain of Responsibility (requests through a chain of candidates) Command (encapsulates a request) Interpreter (grammar.
Design Patterns 2 Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Copyright © Active Frameworks Inc. - All Rights Reserved.More On Behavioral Patterns - Page L9-1 PS95&96-MEF-L16-1 Dr. M.E. Fayad Creationa l.
Winter 2007ACS-3913 Ron McFadyen1 Observer Pattern Problem: There are many objects (observers / subscribers) needing to know of the state changes, or events,
14-Jul-15 Model-View-Controller. 2 Design Patterns The hard problem in O-O programming is deciding what objects to have, and what their responsibilities.
Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes.
Design Patterns.
CS 537 Group 3 Report: Activity Diagrams and Observer Design Pattern Anna Deghdzunyan Xuan Yang Keenan Knaur John Hurley.
02 - Behavioral Design Patterns – 2 Moshe Fresko Bar-Ilan University תשס"ח 2008.
Observer Design Pattern Source: Design Patterns – Elements of Reusable Object- Oriented Software; Gamma, et. al.
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)
Design Patterns Lecture III. What Is A Pattern? Current use comes from the work of the architect Christopher Alexander Alexander studied ways to improve.
Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.
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
(c) University of Washington08-1 CSC 143 Models and Views Reading: Ch. 18.
Chapter 19 Designing the GUI front-end: the Model-View-Controller pattern.
Behavioral Pattern: Observer C h a p t e r 5 – P a g e 186 A large monolithic design does not scale well as additional graphical and monitoring requirements.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns VII Observer, Command, and Memento.
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.
Design Patterns Model – View – Controller. Copyright © 2001 DeLorme 28 November 2001 History ► A framework pattern for reusable applications. ► Depends.
1 Block1 – unit 2 (The Case study in Budd 5-6).  create a small application that uses the Abstract Windowing Toolkit (AWT)  Swing packages to simulate.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
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 A Brief Introduction to Design Patterns Based on materials from Doug Schmidt 1.
CSC 313 – Advanced Programming Topics. Observer Pattern in Java  Java ♥ Observer Pattern & uses everywhere  Find pattern in JButton & ActionListener.
Where Do Surrogates Fit into This Proxy Pattern Observer Pattern Visitor Pattern By Kurt Rehwinkel.
BallWorld.java A structured walkthrough. Key Features: 2 classes are created Execution is done through the procedure called “main” which are decleared.
Proxy, Observer, Symbolic Links Rebecca Chernoff.
Behavioural Design Patterns Quote du jour: ECE450S – Software Engineering II I have not failed. I've just found 10,000 ways that won't work. - Thomas Edison.
Manali Joshi1 The Observer Design Pattern Presented By: Manali Joshi.
BallWorld.java Ball.java A functional walkthrough Part 3: the interaction of objects.
Behavioral Patterns1 Nour El Kadri SEG 3202 Software Design and Architecture Notes based on U of T Design Patterns class.
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.
The Observer Pattern.
The Observer Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
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.
Observer / Observable COMP 401 Fall 2014 Lecture 14 10/7/2014.
Observer Pattern Keeping An Eye on Things Need to introduce observer pattern formally first, include book definition & design principle Keeping An Eye.
OBSERVER PATTERN OBSERVER PATTERN Presented By Presented By Ajeet Tripathi ISE
The Observer Design Pattern Author :Erich Gamma, et al. Source :Elements of Reusable Object-Oriented Software Speaker : Chiao-Ping Chang Advisor : Ku-Yaw.
February 23, 2009Observer Pattern, OOA&D, Rubal Gupta, CSPP, Winter ‘09 Observer Pattern Defines a “one-to-many” dependency between objects so that when.
GUI- Model-View-Controller
Behavioral Patterns Algorithms and the assignment of responsibilities among objects Describe not just patterns of objects or classes but also the patterns.
Observer Pattern Context:
Observer Design Pattern
Observer Design Pattern
Architectural Patterns for Interactive Software
Design Patterns Model – View – Controller
Design Patterns - A few examples
Introduction to Behavioral Patterns (1)
Introduction to Event Handling
Observer Pattern 1.
Advanced ProgramMING Practices
8. Observer Pattern SE2811 Software Component Design
Advanced ProgramMING Practices
Software Design Lecture : 40.
GUI- Model-View-Controller
Presentation transcript:

OBSERVER DESIGN PATTERN

Behavioral Patterns  Behavioral patterns are those patterns that are most specifically concerned with communication between objects

Introduction  Name  Observer  Also Known As  Dependents, Publish-Subscribe

Observer  Intent  Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically  Use the Observer pattern:  When an abstraction has two aspects, one dependent on the other.  When a change to one object requires changing others, and you don't know how many objects need to be changed  When an object should be able to notify other objects without making assumptions about who these objects are.

Structure

Participants  Subject  knows its observers. Any number of Observer objects may observe a subject.  provides an interface for attaching and detaching Observer objects.  Observer  defines an updating interface for objects that should be notified of changes in a subject.  ConcreteSubject  stores state of interest to ConcreteObserver objects.  sends a notification to its observers when its state changes.  ConcreteObserver  maintains a reference to a ConcreteSubject object.  stores state that should stay consistent with the subject's.  implements the Observer updating interface to keep its state consistent with the subject's.

Collaborations

SpreadSheet Example

 How to implement a spreadsheet?

Java's Implementation  Java API implements a framework for this pattern  Java's observer interface is the Observer abstract class in the pattern  Java's Observable class is the Subject abstract class in the pattern  Class java.util.Observable  Observable object may have any number of Observers  Whenever the Observable instance changes, it notifies all of its observers  Notification is done by calling the update() method on all observers.  Interface java.util.Observer  When implemented, this interface allows all classes to be observable by instances of class Observer

java.util.Observable Methods  addObserver(Observer)  Adds an observer to the observer list.  countObservers()  Counts the number of observers.  deleteObserver(Observer)  Deletes an observer from the observer list.  deleteObservers()  Deletes observers from the observer list.  hasChanged()  Returns a true boolean if an observable change has occurred.

java.util.Observable Methods  notifyObservers()  Notifies all observers if an observable change occurs.  notifyObservers(Object)  Notifies all observers of the specified observable change which occurred.  setChanged()  Sets a flag to note an observable change.  Interface java.util.Observer  Update() Called when observers in the observable list need to be updated

A Java Example  The Classes indicates interface

Class Descriptions Counter A Counter can increase or decrease by one. Each time a counter changes value, it notifies its observers of the type of change. IncreaseDectector IncreaseDetector is an observer that observes counters. IncreaseDetector counts the number of times one of its observables increases. It notifies its observers when it changes

Class Descriptions CounterButton Abstract class for changing a counter each time the button is pressed IncreaseButton A button that increases a counter each time the button is pressed DecreaseButton A button that decreases a counter each time the button is pressed

Class Descriptions CounterView A parent window view that observes a counter. Does nothing with counter. Used as parent for other views. CounterTextView A window for displaying the value of a counter in ASCII. ButtonController A window for changing the value of a counter using IncreaseButton and DecreaseButton. RectangleView Draws a colored rectangle that depends on two counters. One counter is the width of the rectangle, the other counter is the height of the rectangle. The color of rectangle varies with its shape.

class Counter /** A counter can increase/decrease by 1. Each time a counter changes value, it notifies its observers of the type of change. */ class Counter extends Observable { public static final String INCREASE = "increase"; public static final String DECREASE = "decrease"; private int count = 0; private String label; public Counter( String label ) { this.label = label; } public String label() { return label; } public int value() { return count; } public String toString() { return String.valueOf( count );} public void increase() { count++; setChanged(); notifyObservers( INCREASE ); } public void decrease() { count--; setChanged(); notifyObservers( DECREASE ); }

class IncreaseDetector /** * IncreaseDetector is an observer that observes counters. *IncreaseDetector counts the number of times one of its * observables increases. */ class IncreaseDetector extends Counter implements Observer { public IncreaseDetector( String label ) { super( label ); } public void update( Observable whatChanged, Object message) { if ( message.equals( Counter.INCREASE) ) increase(); }

abstract class CounterButton /** * An abstract class for changing a counter each time the button is pressed */ abstract class CounterButton extends Button { protected Counter count; public CounterButton( String buttonName, Counter count ) { super( buttonName ); this.count = count; } public boolean action( Event processNow, Object argument ) { changeCounter(); return true; } abstract protected void changeCounter(); }

class IncreaseButton /** * A button that increases a counter each time it is pressed */ class IncreaseButton extends CounterButton { public IncreaseButton( Counter count ) { super( "Increase", count ); } protected void changeCounter() { count.increase(); }

class DecreaseButton /** * A button that decreases a counter each time it is pressed */ class DecreaseButton extends CounterButton { public DecreaseButton( Counter count ) { super( "Decrease", count ); } protected void changeCounter() { count.decrease(); }

class CounterView /** * A parent window view that observes a counter */ class CounterView extends Frame implements Observer { public CounterView( String label, int x, int y, int width, int height ) { setTitle( label ); reshape(x, y, width, height ); setLayout( new FlowLayout() ); } /** * Redraw the window when an observed counter changes */ public void update(Observable counter, Object argument) { repaint(); }

class CounterTextView /** * A window for displaying the value of a counter in ascii */ class CounterTextView extends CounterView { Counter model; public CounterTextView( Counter model, String label, int x, int y, int width, int height ) { super( label, x, y, width, height ); this.model = model; model.addObserver( this ); show(); } public void paint( Graphics display ) { int y = bounds().height - 20; int x = 20; display.drawString( "The value of " + model.label() + " is " + model, x, y ); }

class ButtonController /** * A window for changing the value of a counter */ class ButtonController extends CounterView { public ButtonController( Counter model, int x, int y, int width, int height ) { super( model.label(), x, y, width, height ); model.addObserver( this ); // show the value of the counter new CounterTextView( model, "Value of " + model.label(), x + width + 5,y, 150, 50); // buttons to change counter add( new IncreaseButton( model )); add( new DecreaseButton( model )); show(); }

class RectangleView /** * Draws a colored rectangle that depends on two counters. One counter is the width, the other counter is the height of the rectangle. The color of rectangle varies with its shape */ class RectangleView extends CounterView { Counter width; Counter height; public RectangleView( Counter rectWidth, Counter rectHeight, int x, int y ) { super( "Rectangle", x, y, 150, 150 ); height = rectHeight; width = rectWidth; rectWidth.addObserver( this ); rectHeight.addObserver( this ); show(); }

class RectangleView Continued public void paint( Graphics display ) { int x = 10; int y = 10; // Magnify value by 5 to get a bigger visual effect int height = 5 * this.height.value(); int width = 5 * this.width.value(); // Determine color. Colors chosen for fun. // The factor of 3 is just to magnify effect of change if (( width >= 0 ) && ( height >= 0 )) display.setColor( new Color( 3*width, 3*height, width + height) ); else if (( width = 0 )) display.setColor( Color.pink ); else if (( width >= 0 ) && ( height < 0 )) display.setColor( Color.orange ); else if (( width < 0 ) && ( height < 0 )) display.setColor( Color.red ); display.fillRect(x, y, Math.abs(width), Math.abs( height ) ); }

Sample Program class TestButton { public static void main( String args[] ) { Counter x = new Counter( "x" ); Counter y = new Counter( "y" ); IncreaseDetector plus = new IncreaseDetector( "Pluses" ); x.addObserver( plus ); y.addObserver( plus ); new ButtonControler( x, 30, 30, 150, 50 ); new ButtonControler( y, 30, 100, 150, 50 ); new CounterTextView( plus, "# of increases", 30, 170, 150, 50); new RectangleView( x, y, 340, 30 ); }

Sample Program

Runtime Object Interaction

Consequences  Abstract coupling between Subject and Observer  Support for broadcast communication  Unexpected updates  Simple change in subject can cause numerous updates, which can be expensive or distracting  Updates can take too long  Subject can not perform any work until all observers are done

Implementation Issues  Mapping subjects(Observables) to observers  Use list (or hash table) in subject  Observing more than one subject  If an observer has more than one subject how does it know which one changed?  Pass information in the update method  Dangling references to Deleted Subjects  Deleting a subject should not produce dangling references in its observers  Make the subject notify its observers  deleting the observers is not an option

Push Model  At one extreme, which we call the push model  The subject sends observers detailed information about the change, whether they want it or not  the push model assumes subjects know something about their observers' needs  The push model might make observers less reusable  Subject classes make assumptions about Observer classes that might not always be true

Pull Model  At the other extreme is the pull model  the subject sends nothing but the most minimal notification, and observers ask for details explicitly thereafter  The pull model emphasizes the subject's ignorance of its observers  the pull model may be inefficient  Observer classes must ascertain what changed without help from the Subject