Behavioral Patterns Algorithms and the assignment of responsibilities among objects Describe not just patterns of objects or classes but also the patterns.

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

 Recent researches show that predicative programming can be used to specify OO concepts including classes, objects, interfaces, methods, single and multiple.
Observer Method 1. References Gamma Erich, Helm Richard, “Design Patterns: Elements of Reusable Object- Oriented Software” 2.
March Ron McFadyen1 Design Patterns In software engineering, a design pattern is a generally repeatable solution to a commonly-occurring problem.
March Ron McFadyen1 Observer P Also known as Publish-Subscribe Applied in order to implement the Model-View Separation principle (see.
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.
March Ron McFadyen1 Design Patterns In software engineering, a design pattern is a generally repeatable solution to a commonly-occurring problem.
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,
Io package as Java’s basic I/O system continue’d.
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.
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
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.
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.
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.
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.
OBSERVER DESIGN PATTERN. Behavioral Patterns  Behavioral patterns are those patterns that are most specifically concerned with communication between.
Manali Joshi1 The Observer Design Pattern Presented By: Manali Joshi.
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 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.
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.
Dec 2005 MSc Slide 1 Pattern that are most specifically concerned with communication between objects Cat 3: Behavioral Patterns.
GUI- Model-View-Controller
Observer Pattern Context:
Delegates and Events 14: Delegates and Events
Observer Design Pattern
Observer Design Pattern
Architectural Patterns for Interactive Software
Design Patterns Model – View – Controller
MVC Paradigm The MVC paradigm breaks applications or interfaces into three parts: the model, the view, and the controller. A --> 25 % B --> 60 % C -->
Design Patterns - A few examples
Introduction to Behavioral Patterns (1)
Introduction to Event Handling
Patterns.
Observer Pattern 1.
Behavioral Design Pattern
Observer Design Pattern
Design pattern Lecture 9.
Advanced ProgramMING Practices
Design Patterns Lecture part 1.
8. Observer Pattern SE2811 Software Component Design
Advanced ProgramMING Practices
Module 18: Design Patterns
Software Design Lecture : 39.
Software Design Lecture : 40.
GUI- Model-View-Controller
Presentation transcript:

Behavioral Patterns Algorithms and the assignment of responsibilities among objects Describe not just patterns of objects or classes but also the patterns of communication between them Shift your focus away from flow of control to let you concentrate just on the way objects are interconnected Observer

Behavioral Patterns - Observer Intent Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. Applicability An abstraction has two aspects, one dependent on the other. When changing one object requires changing others, and you don’t know how many objects need changed. When an object needs to notify others without knowledge about who they are.

Behavioral Patterns - Observer An Example

Behavioral Patterns - Observer Strucuture: Class Diagram Subject <<interface>> * Observer attach( observer ) detach( observer ) observers update() notify() for all o in observers o.update() observerState := ConcreteSubject subject.getState() ConcreteObserver subjectState subject getState() update()

Behavioral Patterns - Observer Participants Subject Knows its observers, but not their “real” identity. Provides an interface for attaching/detaching observers. Observer Defines an updating interface for objects that should be identified of changes. ConcreteSubject Stores state of interest to ConcreteObserver objects. Sends update notice to observers upon state change. ConcreteObserver Maintains reference to ConcreteSubject (sometimes). Maintains state that must be consistent with ConcreteSubject. Implements the Observer interface. Collaborations ConcreteSubject notifies observers when changes occur. ConcreteObserver may query subject regarding state change.

Behavioral Patterns - Observer Sequence Diagram subject : observer1 : observer2 : ConcreteSubject ConcreteObserver ConcreteObserver attach( observer1 ) attach( observer2 ) notify() update() getState() update() getState()

Behavioral Patterns - Observer Consequences Benefits Abstract coupling between Subject and Observer Can reuse subjects without reusing their observers and vice versa Observers can be added without modifying the subject All subject knows is its list of observers Subject does not need to know the concrete class of an observer, just that each observer implements the update interface Subject and observer can belong to different abstraction layers Support for broadcast communication: subject sends notification to all subscribed observers Observers can be added/removed at any time Liabilities Possible cascading of notifications Observers are not necessarily aware of each other and must be careful about triggering updates Simple update interface requires observers to deduce changed item

Behavioral Patterns - Observer Implementation How does the subject keep track of its observers? Array, linked list What if an observer wants to observe more than one subject? Have the subject tell the observer who it is via the update interface Who triggers the update? The subject whenever its state changes The observers after they cause one or more state changes Some third party object(s) Make sure the subject updates its state before sending out notifications How much info about the change should the subject send to the observers? Push Model - Lots Pull Model - Very Little

Behavioral Patterns - Observer Implementation Can the observers subscribe to specific events of interest? If so, it's publish-subscribe Can an observer also be a subject? What if an observer wants to be notified only after several subjects have changed state? Use an intermediary object which acts as a mediator Subjects send notifications to the mediator object which performs any necessary processing before notifying the observers

Behavioral Patterns - Observer MVC Example 1 This example shows the model and the view in the same class /** * Class CounterGui demonstrates having the model and view * in the same class. */ public class CounterGui extends Frame { // The counter. (The model!) private int counter = 0; // The view. private TextField tf = new TextField(10);

Behavioral Patterns - Observer MVC Example 1 public CounterGui(String title) { super(title); Panel tfPanel = new Panel(); tf.setText("0"); tfPanel.add(tf); add("North", tfPanel); Panel buttonPanel = new Panel(); Button incButton = new Button("Increment"); incButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { counter++; tf.setText(counter + ""); } } ); buttonPanel.add(incButton);

Behavioral Patterns - Observer MVC Example 1 Button decButton = new Button("Decrement"); decButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { counter--; tf.setText(counter + ""); } } ); buttonPanel.add(decButton); Button exitButton = new Button("Exit"); exitButton.addActionListener(new ActionListener() { System.exit(0); buttonPanel.add(exitButton); add("South", buttonPanel);

Behavioral Patterns - Observer MVC Example 1 addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); public static void main(String[] argv) { CounterGui cg = new CounterGui("CounterGui"); cg.setSize(300, 100); cg.setVisible(true); Where is the controller in this example? The controllers are the instances of the anonymous classes which handle the button presses.

Behavioral Patterns - Observer MVC Example 2 This example shows the model and the view in separate classes First the view class: /** * Class CounterView demonstrates having the model and view * in the separate classes. This class is just the view. */ public class CounterView extends Frame { // The view. private TextField tf = new TextField(10); // A reference to our associated model. private Counter counter;

Behavioral Patterns - Observer MVC Example 2 public CounterView(String title, Counter c) { super(title); counter = c; Panel tfPanel = new Panel(); tf.setText(counter.getCount()+ ""); tfPanel.add(tf); add("North", tfPanel); Panel buttonPanel = new Panel(); Button incButton = new Button("Increment"); incButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { counter.incCount(); tf.setText(counter.getCount() + ""); } } ); buttonPanel.add(incButton);

Behavioral Patterns - Observer MVC Example 2 Button decButton = new Button("Decrement"); decButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { counter.decCount(); tf.setText(counter.getCount()+ ""); } } ); buttonPanel.add(decButton); Button exitButton = new Button("Exit"); exitButton.addActionListener(new ActionListener() { System.exit(0); buttonPanel.add(exitButton); add("South", buttonPanel);

Behavioral Patterns - Observer MVC Example 2 addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); public static void main(String[] argv) { Counter counter = new Counter(0); CounterView cv1 = new CounterView("CounterView1", counter); cv1.setSize(300, 100); cv1.setVisible(true); CounterView cv2 = new CounterView("CounterView2", counter); cv2.setSize(300, 100); cv2.setVisible(true);

Behavioral Patterns - Observer MVC Example 2 Next the model class: /** * Class Counter implements a simple counter model. */ public class Counter { // The model. private int count; public Counter(int count) { this.count = count; } public int getCount() { return count; } public void incCount() { count++; } public void decCount() { count--; } }

Behavioral Patterns - Observer MVC Example 2 Note that we instantiated one model and two views in this example: But we have a problem! When the model changes state, only one view updates! We need the Observer Pattern here!

Behavioral Patterns - Observer MVC Example 3 This example shows the model and the view in separate classes with the model being observable. First the model class: import java.util.Observable; /** * Class ObservableCounter implements a simple observable counter model. */ public class ObservableCounter extends Observable { // The model. private int count; public ObservableCounter(int count) { this.count = count; }

Behavioral Patterns - Observer MVC Example 3 public int getCount() { return count; } public void incCount() { count++; setChanged(); notifyObservers(); } public void decCount() { count--;

Behavioral Patterns - Observer MVC Example 3 Next the view class: /** * Class ObservableCounterView demonstrates having the model * and view in the separate classes. This class is just the * view. */ public class ObservableCounterView extends Frame { // The view. private TextField tf = new TextField(10); // A reference to our associated model. private ObservableCounter counter;

Behavioral Patterns - Observer MVC Example 3 public ObservableCounterView(String title, ObservableCounter c) { super(title); counter = c; // Add an anonymous observer to the ObservableCounter. counter.addObserver(new Observer() { public void update(Observable src, Object obj) { if (src == counter) { tf.setText(((ObservableCounter)src).getCount() + ""); } } ); // Same GUI code as Example 2 not shown...

Behavioral Patterns - Observer MVC Example 3 public static void main(String[] argv) { ObservableCounter counter = new ObservableCounter(0); ObservableCounterView cv1 = new ObservableCounterView("ObservableCounterView1", counter); cv1.setSize(300, 100); cv1.setVisible(true); ObservableCounterView cv2 = new ObservableCounterView("ObservableCounterView2", counter); cv2.setSize(300, 100); cv2.setVisible(true); }

Behavioral Patterns - Observer MVC Example 3 Looking good now!

Appendix: More on the Observer Pattern Decouples a subject and its observers Widely used in Smalltalk to separate application objects from interface objects Known in the Smalltalk world as Model-View-Controller (MVC) Rationale: the interface is very likely to change while the underlying business objects remain stable Defines a subject (the Observable) that is observed Allows multiple observers to monitor state changes in the subject without the subject having explicit knowledge about the existence of the observers Useful ... When you have two objects, 1 is going to change and 1 is going to change over time. Example, GUI’s. The underlying model of UI was stable and the GUI’s were not Observer Subject Observer Observer 10

More on the Observer Pattern The Model-View-Controller (MVC) Developed at Xerox Parc to provide foundation classes for Smalltalk-80 The Model, View and Controller classes have more than a 10 year history Fundamental Principle separate the underlying application MODEL (business objects) from the INTERFACE (presentation objects) Rationale for MVC: Design for change and reuse Expert Interface Business Objects (the Model in MVC) Novice Interface MVC and Observer Pattern In Smalltalk, objects may have dependents When an object announces “I have changed”, its dependents are notified It is the responsibility of the dependents to take action or ignore the notification 11

More on the Observer Pattern java.util.Observable Observable/subject objects (the Model in Model-View) can announce that they have changed Methods: void setChanged() void clearChanged() boolean hasChanged() WHAT IF Observers query a Subject periodically? query Subject Observer setChanged() hasChanged() Harry True/false 16

More on the Observer Pattern Implementing & Checking an Observable Implementing an Observable Checking an Observable import java.util.*; import java.io.*; public class Harry extends Observable { private boolean maritalStatus = false; public Harry (boolean isMarried) { maritalStatus = isMarried; } public void updateMaritalStatus (boolean change) { maritalStatus = change; // set flag for anyone interested to check this.setChanged(); public static void main (String args [ ] ) { Harry harry = new Harry (false); harry.updateMaritalStatus (true); if (harry.hasChanged() ) System.out.println ("Time to call harry"); } 17

Appendix: More on the Observer Pattern WHAT IF Observers query a Subject periodically? Good or Bad? + Good: Any object can observe by calling hasChanged() - Bad: the observer must actively call hasChanged() ? What’s the alternative? Automatic notification -> Observer pattern 20

Appendix: More on the Observer Pattern Implementing the Observer Pattern Step 1: Observers register with Observable addObserver (this) Observer1 Harry addObserver (observer2) Observer2 Step 2. Observable notifies Observers notifyObservers(Object arg) update(Observable o, Object arg) Harry Observer1 Observable (Harry) may also send himself a notifyObservers() msg - no params 24

Appendix: More on the Observer Pattern java.util.Observable The superclass of all ‘observable’ objects to be used in the Model View design pattern Methods are provided to: void addObserver(anObserver) int countObservers() void deleteObserver (anObserver) void deleteObservers () Interface Defines the update() method that allows an object to ‘observe’ subclasses of Observable Objects that implement the interface may be passed as parameters in: addObserver(Observer o) 26