Programming in C# Observer Design Pattern

Slides:



Advertisements
Similar presentations
Patterns of Interaction 2: Publish-Subscribe CS 5010 Program Design Paradigms "Bootcamp" Lesson 11.6 © Mitchell Wand, This work is licensed under.
Advertisements

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)
1 Dept. of Computer Science & Engineering, York University, Toronto CSE3311 – Software Development Observer Pattern.
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.
Chapter 2: The Observer Pattern. Consider the Following Application Application specification Humidity Temperature Pressure Weather Station Weather Data.
Figures – Chapter 7.
Design Patterns Pepper. Find Patterns Gang of Four created 23 Siemens published another good set x
Chapter 7 – Object-Oriented Design
March Ron McFadyen1 Design Patterns In software engineering, a design pattern is a generally repeatable solution to a commonly-occurring problem.
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.
The Observer Pattern. Formal Definition Define a one-to-many dependency between objects so that when one object changes state, all its dependents are.
March Ron McFadyen1 Design Patterns In software engineering, a design pattern is a generally repeatable solution to a commonly-occurring problem.
Oct Ron McFadyen1 Collaborations Collaboration : an arrangement of classes, links, roles in a context to implement some behaviour. Useful for.
Winter 2007ACS-3913 Ron McFadyen1 Observer Pattern Problem: There are many objects (observers / subscribers) needing to know of the state changes, or events,
ECE 355 Design Patterns Tutorial Part 2 (based on slides by Ali Razavi) Presented by Igor Ivković
PRESENTED BY SANGEETA MEHTA EECS810 UNIVERSITY OF KANSAS OCTOBER 2008 Design Patterns.
Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes.
Design Patterns.
Basic OOP in C#.
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.
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.
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.
Behavioral Design Patterns Morteza Yousefi University Of Science & Technology Of Mazandaran 1of 27Behavioral Design Patterns.
Where Do Surrogates Fit into This Proxy Pattern Observer Pattern Visitor Pattern By Kurt Rehwinkel.
Observer Please Snarf the Code for Today’s Class..
Design Patterns. OO-Concepts Don’t rewrite code Encapsulation Inheritance Write flexible code.
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.
Design Pattern. Definition: A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design.
Observer Design Pattern
OBSERVER DESIGN PATTERN. Behavioral Patterns  Behavioral patterns are those patterns that are most specifically concerned with communication between.
CSE 332: Design Patterns Review: Design Pattern Structure A design pattern has a name –So when someone says “Adapter” you know what they mean –So you can.
Manali Joshi1 The Observer Design Pattern Presented By: Manali Joshi.
CS 415 N-Tier Application Development By Umair Ashraf June 22,2013 National University of Computer and Emerging Sciences Lecture # 3 Design Patterns (Observer,Factory,Singleton)
Behavioral Patterns1 Nour El Kadri SEG 3202 Software Design and Architecture Notes based on U of T Design Patterns class.
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.
CS 210 Review October 3, 2006.
Events Programming in C# Events CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
Watching the movie the hard way…. Page 256 – Head First Design Patterns.
The Observer Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
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.
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.
Observer Pattern Context:
Slide design: Dr. Mark L. Hornick
Observer Design Pattern
CMPE 135: Object-Oriented Analysis and Design October 24 Class Meeting
Observer Design Pattern
Presented by Igor Ivković
OO Design - Observer Pattern
Introduction to Behavioral Patterns (1)
CMPE 135 Object-Oriented Analysis and Design March 21 Class Meeting
Advanced ProgramMING Practices
Design Patterns Lecture part 1.
8. Observer Pattern SE2811 Software Component Design
Presented by Igor Ivković
Software Design Lecture 11.
Presentation transcript:

Programming in C# Observer Design Pattern CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis

Keeping Objects Informed A very common requirement in any complex system is the ability for an object to know whenever an event happens or whenever another object changes its state (which can also be viewed as an event). Examples: Interest rates lowered File I/O request is complete Mouse button was depressed.

Polling vs. Notification There are two primary approaches: Polling – Any object that is interested in state changes will periodical inquire the state. Difficult to get to work with events. Notification – Objects register to receive an update or notification whenever state changes or an event occurs. A publisher ensures that everyone is notified. Observer Design Pattern

Observer Pattern This one of the common design patterns published by Gamma, et. al. Also goes by the name Publisher-Subscriber. When one object changes state, all the dependent objects are notified and updated. Allows for consistency between related objects without tightly coupling classes e.g. “reduces coupling between objects”

A Problem Multiple displays need to be updated with weather data from a single weather station ©Head First Design Patterns, Freeman and Freeman, p. 39

A naive solution public class WeatherData { // instance variable declarations public void MeasurementsChanged() { float temperature = getTemperature(); float humidity = getHumidity(); float pressure = getPressure(); currentConditionsDisplay.update( temperature, humidity, pressure); statisticsDisplay.Update( temperature, humidity, pressure); forecastDisplay.Update( temperature, humidity, pressure); } // other weather data methods here

Problems with this Solution Identify the aspects of your application that vary and separate them from what stays the same. Program to an interface, not an implementation. Strive for loosely coupled designs between objects that interact. – fails – fails – fails

The Observer Pattern The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified.

Key Players Subject Interface Observer Interface ConcreteSubject Knows its observers – provides interface for attaching/detaching subjects Observer Interface Defines an interface for notifying the subjects of changes to the object (ex. Data) ConcreteSubject Sends notification to observers when state changes ConcreteObserver Implements Observer interface

Code Example public interface IPublisher {   public void AddSubscriber( ISubscriber subscriber );   public void RemoveSubscriber( ISubscriber subscriber ); } public interface ISubscriber {   public void Update( object sender );

Consequences Abstract coupling between subject and observer This is perhaps too abstract. Usually have a more semantic-based interface. Abstract coupling between subject and observer Coupling is abstract, thus minimal (concrete class isn’t known) Can have multiple layers of abstraction Support for broadcast communication Subject doesn’t need to know its receivers or even how many subscribers it has.

Implementing to Interfaces public interface IWeatherPublisher {   void AddSubscriber( IWeatherObserver subscriber );   void RemoveSubscriber( IWeatherObserver subscriber ); } public interface IWeatherObserver {   void Update( float temp, float humidity, float pressure ); public interface DisplayElement { void Display();

Implementing IWeatherPublisher public class WeatherData : IWeatherPublisher { private IList<IWeatherObserver> observers = new List<IWeatherObserver>(); private float temperature; private float humidity; private float pressure; public void AddSubscriber( IWeatherObserver subscriber ) { observers.Add( subscriber ); } public void RemoveSubscriber( IWeatherObserver subscriber ) { if( !observers.Contains(subscriber) ) throw new ArguementException(“Subscriber does not exist”); observers.Remove(subscriber);

Implementing IWeatherPublisher public void SetMeasurements( float temperature, float humidity, float pressure) { this.temperature = temperature; this.humidity = humidity; this.pressure = pressure; notifyObservers(); } private void NotifyObservers() { foreach (IWeatherObserver observer in observers) { observer.Update( temperature, humidity, pressure ); // other WeatherData methods here - getters

Implementing Observers public class CurrentConditionsDisplay : IWeatherObserver , DisplayElement { private float temperature; private float humidity; public CurrentConditionsDisplay( IWeatherPublisher weatherData ) { weatherData.AddSubscriber( this ); } public void Update( float temperature, float humidity, float pressure ) { this.temperature = temperature; this.humidity = humidity; Display(); public void Display() { System.Console.Writeline( "Current conditions: " + temperature + "F degrees and " + humidity + "% humidity");

Push vs Pull This solution pushes data to the observers public void Update( float temperature, float humidity, float pressure) { this.temperature = temperature; this.humidity = humidity; Display(); } The observers may not use all of the data or may need different data? Observers can pull the specific data they need from the subject public void Update( IWeatherPublisher weatherData ) { this.temperature = weatherData.Temperature; this.humidity = weatherData.Humidity;

Loose Coupling When two objects are loosely coupled, they can interact, but have very little knowledge of each other. The Observer Pattern provides an object design where subjects and observers are loosely coupled. The only thing the subject knows about an observer is that it implements a certain interface We can add new observers at any time. We never need to modify the subject to add new types of observers. We can reuse subjects or observers independently of each other. Changes to either the subject or an observer will not affect the other.

Observer Pattern in C# This pattern is so prevalent, that C# added language support for it (as opposed to class libraries). The next topic will present the event keyword in C#. Events combined with delegates provide first-class support for the Observer Pattern in C#.

Programming in C# Observer Design Pattern CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis