Observer
This presentation is the property of its rightful owner.
Sponsored Links
1 / 27

Observer PowerPoint PPT Presentation


  • 110 Views
  • Uploaded on
  • Presentation posted in: General

Observer. Behavioral Pattern. Intent. Define a one-to-many dependency between objects so that when one object changes state , all its dependents are notified and updated automatically. A.k.a Dependents, Publish-Subscribe. Motivation.

Download Presentation

Observer

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Observer

Observer

Behavioral Pattern


Intent

Intent

  • Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

  • A.k.aDependents, Publish-Subscribe


Motivation

Motivation

  • A common side-effect of partitioning a system into a collection of cooperating classes is the need to maintain consistency between related objects. You don‘t want to achieve consistency by making the classes tightly coupled, because that reduces their reusability

  • For example, many graphical user interface toolkits separate the presentational aspects of the user interface from the underlying application data. Classes defining application data and presentations can be reused independently. They can work together, too.

  • Both a spreadsheet object and bar chart object can depict information in the same application data object using different presentations. The spreadsheet and the bar chart don't know about each other, thereby letting you reuse only the one you need. But they behave as though they do. When the user changes the information in the spreadsheet, the bar chart reflects the changes immediately, and vice versa


Motivation1

Motivation

  • This behavior implies that the spreadsheet and bar chart are dependent on the data object and therefore should be notified of any change in its state. And there’s no reason to limit the number of dependent objects to two; there may be any number of different user interfaces to the same data

  • The Observer pattern describes how to establish these relationships. The key objects in this pattern are subject and observer. A subject may have any number of dependent observers. All observers are notified whenever the subject undergoes a change in state. In response, each observer will query the subject to synchronize its state with the subject's state


Motivation2

Motivation

  • This kind of interaction is also known as publish-subscribe. The subject is the publisher of notifications. It sends out these notifications without having to know who its observers are. Any number of observers can subscribe to receive notifications


Applicability

Applicability

  • Use the Observer pattern in any of the following situations:

    • When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently.

    • 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. In other words, you don't want these objects tightly coupled.


Structure

Structure


Participants

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 Concrete Observer objects.

    • sends a notification to its observers when its state changes.

  • ConcreteObserver

    • maintains a reference to a Concrete Subject 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

Collaborations

  • ConcreteSubject notifies its observers whenever a change occurs that could make its observers' state inconsistent with its own.

  • After being informed of a change in the concrete subject, a ConcreteObserver object may query the subject for information. ConcreteObserveruses this information to reconcile its state with that of the subject.


Collaborations1

Collaborations

  • Note how the Observer object that initiates the change request postpones its update until it gets a notification from the subject. Notify is not always called by the subject. It can be called by an observer or by another kind of object entirely.


Consequences

Consequences

  • The Observer pattern lets you vary subjects and observers independently. You can reuse subjects without reusing their observers, and vice versa. It lets you add observers without modifying the subject or other observers

  • Abstract coupling between Subject and Observer– All a subject knows is that it has a list of observers, each conforming to the simple interface of the abstract Observer class. The subject doesn't know the concrete class of any observer. Thus the coupling between subjects and observers is abstract and minimal


Consequences1

Consequences

  • Support for broadcast communication– Unlike an ordinary request, the notification that a subject sends needn't specify its receiver. The notification is broadcast automatically to all interested objects that subscribed to it. The subject doesn't care how many interested objects exist; its only responsibility is to notify its observers. This gives you the freedom to add and remove observers at any time. It's up to the observer to handle or ignore a notification


Weather monitoring application

Weather Monitoring Application

Humidity

Sensor

Pulls

Data

Weather

Station

displays

Weather Data

Object

Display

Device

Temp

Sensor

Pressure

Sensor


What needs to be done

/*

* Call this method

* whenever measurements are

* Updated

*/

Public void measurementsChanged(){

// your code goes here

}

WeatherData

getTemperature()

getHumidity()

getPressure()

measurementsChanged()

What needs to be done?

Update three

different displays


Problem specification

Problem specification

  • weatherData class has three getter methods

  • measurementsChanged() method called whenever there is a change

  • Three display methods needs to be supported: current conditions, weather statistics and simple forecast

  • System should be expandable


First cut at implementation

First cut at implementation

public class WeatherData {

public void measurementsChanged(){

float temp = getTemperature();

float humidity = getHumidity();

float pressure = getPressure();

currentConditionsDisplay.update (temp, humidity, pressure);

statisticsDisplay.update (temp, humidity, pressure);

forecastDisplay.update (temp, humidity, pressure);

}

// other methods

}


First cut at implementation1

First cut at implementation

public class WeatherData {

public void measurementsChanged(){

float temp = getTemperature();

float humidity = getHumidity();

float pressure = getPressure();

currentConditionsDisplay.update (temp, humidity, pressure);

statisticsDisplay.update (temp, humidity, pressure);

forecastDisplay.update (temp, humidity, pressure);

}

// other methods

}

Area of change which can be

Managed better by encapsulation

By coding to concrete implementations

there is no way to add additional display

elements without making code change


Basis for observer pattern

Basis for observer pattern

  • Fashioned after the publish/subscribe model

  • Works off similar to any subscription model

    • Buying newspaper

    • Magazines

    • List servers


Observer pattern weather data

<<interface>>

Observer

<<interface>>

DisplayElement

<<interface>>

Subject

update()

display()

registerObserver()

removeObserver()

notifyObservers()

CurrentConditionsDisplay

StatisticsDisplay

update()

display()

update()

display()

ForecastDisplay

update()

display()

Observer Pattern – Weather data

observers

subject

WeatherData

registerObserver()

removeObserver()

notifyObservers()

getTemperature()

getPressure()

measurementsChanged()


Weather data interfaces

Weather data interfaces

public interface subject

{

void registerObserver(Observer o);//Takes observer as an argument

void removeObserver(Observer o);//Takes observer as an argument

void notifyObserver(); //Is called to notify all observers when the subject’s

} // state is changed

public interface Observer

{//The update() gets state values as argument from Subject when weather //measurement changes

void update(float temp,floathumidity,float pressure);

}

public interface DisplayElement

{

void display();

}


Implementing subject interface

Implementing subject interface

public class WeatherData :subject

{

private ArrayList observers; //Array list to hold the observers

private float temperature;

private float humidity;

private float pressure;

public WeatherData()

{

observers=new ArrayList(); // creating the array list in constructor

}


Register and unregister

Register and unregister

public void registerObserver(Observer o) {

observers.Add(o);// when we have a new observer we add it // to the list of observers

}

public void removeObserver(Observer o) {

inti = observers.indexOf(o);

if (i >= 0) {

observers.Remove(i);

}

}


Notify methods

Notify methods

public void notifyObserver()

{// We Notify all observers about the state by calling update() method on all

foreach (Observer obs in observers)

{

obs.update(temperature, humidity, pressure);

}

}

void measurementChanged()

{//We notify the observers when we get updated weather measurements

notifyObserver();

}

public void setMeasurement(float temperature,floathumidity,float pressure)

{//Setting dummy values of weather station

this.temperature = temperature; this.humidity = humidity; this.pressure= pressure;

measurementChanged();

}


Implementing display application

Implementing Display Application

public class currentConditionDisplay: Observer,DisplayElement

{

private float temperature;

private float humidity;

private subject weatherData;

//Passing the subject and using it to register the display as an observer

public currentConditionDisplay(subject weatherData)

{

this.weatherData = weatherData;

weatherData.registerObserver(this);

}

public void update(float temperature, float humidity, float pressure)

{//when update() is called we save the temp and humidity and call display()

this.temperature = temperature;

this.humidity = humidity;

display();

}


Display methods

Display Methods

public void display()

{

Console.WriteLine("Current condition:"+temperature+"F degress and"+humidity+"% humidity");

}


Client class

Client Class

class Program

{

static void Main(string[] args)

{

//Declaring the weather data (subject) object

WeatherDataweatherdata = new WeatherData();

//Creating the display and passing it the subject

currentConditionDisplaycurrentdisplay = new currentConditionDisplay(weatherdata);

//Simulating the three new weather measurements

weatherdata.setMeasurement(80,65,30.4f);

weatherdata.setMeasurement(82,70,29.2f);

weatherdata.setMeasurement(78, 90, 29.2f);

Console.ReadKey();

}

}


Output screen

Output Screen


  • Login