SlideShare une entreprise Scribd logo
1  sur  16
Télécharger pour lire hors ligne
The Observer Pattern
Weather Monitoring Application

                                 Weather Data Object
   Weather Station           Guy that tracks the data
Device that receives the      coming from weather
     weather data            station and updates the
                                      display


                       Display
                 Shows the current
                weather conditions.
Job description

Create an application that uses the weather data
Object to update the three displays for weather
conditions.


The three displays are current conditions, weather
stats and forecast
Weather Data Class
• getTemprature()
• getPressure()
• getHumidity()
• measurementChanged()




 Weather
 Data Class
Our Task


      Implement
 measurementchanged()
   function so that it
  updates the displays
      accordingly
Simple Solution


measurementChanged() {

• Float temp = getTemperature();
• Float Pr= getPressure();
• Float Hum = getHumidity();
• currentConditionsDisplay.update(temp,Pr,Hum);
• statisticsDisplay.update(temp,Pr,Hum);
• forecastDisplay.update(temp,Pr,Hum);
Problems with the previous approach

We are coding to concrete implementation rather then to
an interface.

We have not encapsulated the part that changes from the
part that remains constant. (Display Changes)

We have no way to add or remove the weather displays at
run time.

If we want to add new display we have to alter code.
The Observer Pattern

 Similar to Newspaper subscription.


 Publishers publish and subscribers read.


 Once subscribers unsubscribe publishers wont get anything to read.


 Once subscribers subscribe again they get to read.


 Publishers are Subject and subscribers are Observer.




 “The Observer pattern defines a one to many relationship between a set of
   objects. When the state of one changes it is notified to all the others.”
Design: Class Diagram
<<interface Subject>>   <<interface Observer>>       <<interface Display>>
 Removesubscriber()            update()                      disp()
   addSubscriber()
  notifyObservers()

                           CurrentConditionDisp                    StatisticsDisplay
    WeatherData
                                 Update();                            Update();
    addSubscriber()               disp();                              disp();
 removerSubscriber()
   notifyObservers()
measurementChanged()                             ForecastDisplay
   getTemprature()
     getHumidity()                                 Update();
     getPressure()                                  disp();
Implementation (Subject)
public class WeatherData implements Subject{
      private ArrayList Observers;
      private float temp,press,hum;
      public WeatherData()
      { Observers = new ArrayList();}
      Publc void removeObserver(Observer o)
      {
            int index = Observers.indexOf(o);
           Observers.remove(i);
      }
      Public void notifyObservers()
      {
           for(I =0;i<Observers.length();i++) {
               Observer o = (Observer)Observers.get(i);
               o.update(temp,hum,press);
           }
      }
      Public void measurementChanged()
      {
           notifyObservers();
      }

      public void addObserver(Observer o)
                  {Observers.add(o);}
Implementation (Observer)
public class CurrentConditionsDisplay implements Observer,Display {
private float temp,hum,press;
private Subject weatherData;

public CurrentConditionsDisplay (Subject s){
    this.weatherData = s;
  weatherData.addObserver(this);
}
Public void update(float temp, float press, float hum)
{
    this.temp= temp; this. Press = press;
    display();
}
public void display()
{
    System.out.println(“ The current conditions of temperature are good : “+temp);
}
Java has built in support for Observer
• You don’t have to implement the addObserver,
  removeObserver etc since these are already
  implemented in Observable class (not an
  interface).
• Both are present in the java.util package.
• You can also implement either pull or push style
  to your observers.
• For an object to become Observer:
  – Implement the Observer Interface and call
    addObserver() on any Observable Object.
Cont…
• For the Observable to send notifications:
  – You must first call the protected setChanged() method
    to signify that the state has changed.
  – Then call one of the two notifyObservers() methos
     • notifyObservers()
     • notifyObservers(Object arg)
        – The argument passed is the data Obect.
  – For an Observer
     • Update(Observable o, Object arg)
        – Implements the update method. If you want the push model you
          can put the data in the dataObject else in case of pull method the
          Observer can get the data when ever it wants.
Dark Side of Observer Java Built in Pattern
• The Observable is a class not an interface. Any already
  defined class which has already extended a class can not
  subclass it.
• You cant create your own implementation that plays well
  with Java Built in Observer API.
• Observable protects the setChanged() method hence any
  class has to subclass It if they want to use Observable. This
  hampers the design principle “favor composite over
  inheritance”
• Swing uses the Observer Pattern. Since every button has a
  number of listeners. Listeners are observers which wait for
  any change in the state of the button and respond
  accordingly.
References…

• Head First Design Patterns
Observer Pattern

Contenu connexe

Tendances

Android Application Component: BroadcastReceiver Tutorial
Android Application Component: BroadcastReceiver TutorialAndroid Application Component: BroadcastReceiver Tutorial
Android Application Component: BroadcastReceiver Tutorial
Ahsanul Karim
 

Tendances (20)

Command Pattern
Command PatternCommand Pattern
Command Pattern
 
Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
 
Location-Based Services on Android
Location-Based Services on AndroidLocation-Based Services on Android
Location-Based Services on Android
 
Angular 2 observables
Angular 2 observablesAngular 2 observables
Angular 2 observables
 
Android Application Component: BroadcastReceiver Tutorial
Android Application Component: BroadcastReceiver TutorialAndroid Application Component: BroadcastReceiver Tutorial
Android Application Component: BroadcastReceiver Tutorial
 
RxJS - The Basics & The Future
RxJS - The Basics & The FutureRxJS - The Basics & The Future
RxJS - The Basics & The Future
 
Functional requirements
Functional requirementsFunctional requirements
Functional requirements
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass Slides
 
Angular 6 Form Validation with Material
Angular 6 Form Validation with MaterialAngular 6 Form Validation with Material
Angular 6 Form Validation with Material
 
Angular Lifecycle Hooks
Angular Lifecycle HooksAngular Lifecycle Hooks
Angular Lifecycle Hooks
 
RxJS Evolved
RxJS EvolvedRxJS Evolved
RxJS Evolved
 
NestJS
NestJSNestJS
NestJS
 
How Sentry can help us with bugs
How Sentry can help us with bugsHow Sentry can help us with bugs
How Sentry can help us with bugs
 
Visitor pattern
Visitor patternVisitor pattern
Visitor pattern
 
Python: Common Design Patterns
Python: Common Design PatternsPython: Common Design Patterns
Python: Common Design Patterns
 
Decorator design pattern
Decorator design patternDecorator design pattern
Decorator design pattern
 
Visitor Pattern
Visitor PatternVisitor Pattern
Visitor Pattern
 
Broadcast Receivers in Android
Broadcast Receivers in AndroidBroadcast Receivers in Android
Broadcast Receivers in Android
 
Angular.pdf
Angular.pdfAngular.pdf
Angular.pdf
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 

En vedette

Observer Pattern Khali Young 2006 Aug
Observer Pattern Khali Young 2006 AugObserver Pattern Khali Young 2006 Aug
Observer Pattern Khali Young 2006 Aug
melbournepatterns
 
Design patterns 4 - observer pattern
Design patterns   4 - observer patternDesign patterns   4 - observer pattern
Design patterns 4 - observer pattern
pixelblend
 
Mediator Pattern
Mediator PatternMediator Pattern
Mediator Pattern
Anuj Pawar
 
Konstantin slisenko - Design patterns
Konstantin slisenko - Design patternsKonstantin slisenko - Design patterns
Konstantin slisenko - Design patterns
beloslab
 
Observer Pattern
Observer PatternObserver Pattern
Observer Pattern
Guo Albert
 
Observer pattern, delegate, event, lambda expression
Observer pattern, delegate, event, lambda expressionObserver pattern, delegate, event, lambda expression
Observer pattern, delegate, event, lambda expression
LearningTech
 

En vedette (19)

Observer design pattern
Observer design patternObserver design pattern
Observer design pattern
 
Design patterns - Observer Pattern
Design patterns - Observer PatternDesign patterns - Observer Pattern
Design patterns - Observer Pattern
 
Observer design pattern
Observer design patternObserver design pattern
Observer design pattern
 
Observer Pattern Khali Young 2006 Aug
Observer Pattern Khali Young 2006 AugObserver Pattern Khali Young 2006 Aug
Observer Pattern Khali Young 2006 Aug
 
Design patterns: observer pattern
Design patterns: observer patternDesign patterns: observer pattern
Design patterns: observer pattern
 
Design patterns 4 - observer pattern
Design patterns   4 - observer patternDesign patterns   4 - observer pattern
Design patterns 4 - observer pattern
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
Design pattern - Software Engineering
Design pattern - Software EngineeringDesign pattern - Software Engineering
Design pattern - Software Engineering
 
Mediator Pattern
Mediator PatternMediator Pattern
Mediator Pattern
 
Memento pattern
Memento patternMemento pattern
Memento pattern
 
Mediator pattern
Mediator patternMediator pattern
Mediator pattern
 
Mediator Design Pattern
Mediator Design PatternMediator Design Pattern
Mediator Design Pattern
 
Konstantin slisenko - Design patterns
Konstantin slisenko - Design patternsKonstantin slisenko - Design patterns
Konstantin slisenko - Design patterns
 
L05 Design Patterns
L05 Design PatternsL05 Design Patterns
L05 Design Patterns
 
Observer Pattern
Observer PatternObserver Pattern
Observer Pattern
 
Js design patterns
Js design patternsJs design patterns
Js design patterns
 
Design Pattern - 2. Observer
Design Pattern -  2. ObserverDesign Pattern -  2. Observer
Design Pattern - 2. Observer
 
Observer pattern, delegate, event, lambda expression
Observer pattern, delegate, event, lambda expressionObserver pattern, delegate, event, lambda expression
Observer pattern, delegate, event, lambda expression
 
The Observer Pattern (Definition using UML)
The Observer Pattern (Definition using UML)The Observer Pattern (Definition using UML)
The Observer Pattern (Definition using UML)
 

Similaire à Observer Pattern

Chapter 6 - Process Synchronization
Chapter 6 - Process SynchronizationChapter 6 - Process Synchronization
Chapter 6 - Process Synchronization
Wayne Jones Jnr
 

Similaire à Observer Pattern (20)

RxJava 2 Reactive extensions for the JVM
RxJava 2  Reactive extensions for the JVMRxJava 2  Reactive extensions for the JVM
RxJava 2 Reactive extensions for the JVM
 
Saving lives with rx java
Saving lives with rx javaSaving lives with rx java
Saving lives with rx java
 
Pointer Events Working Group update / TPAC 2023 / Patrick H. Lauke
Pointer Events Working Group update / TPAC 2023 / Patrick H. LaukePointer Events Working Group update / TPAC 2023 / Patrick H. Lauke
Pointer Events Working Group update / TPAC 2023 / Patrick H. Lauke
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
ReactiveCocoa in Practice
ReactiveCocoa in PracticeReactiveCocoa in Practice
ReactiveCocoa in Practice
 
Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroid
 
Rxandroid
RxandroidRxandroid
Rxandroid
 
RxAndroid
RxAndroidRxAndroid
RxAndroid
 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 Slides
 
Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2
 
RxJava@Android
RxJava@AndroidRxJava@Android
RxJava@Android
 
Demystifying Reactive Programming
Demystifying Reactive ProgrammingDemystifying Reactive Programming
Demystifying Reactive Programming
 
Reactive Extensions: classic Observer in .NET
Reactive Extensions: classic Observer in .NETReactive Extensions: classic Observer in .NET
Reactive Extensions: classic Observer in .NET
 
Android Lab Test : Using the sensor gyroscope (english)
Android Lab Test : Using the sensor gyroscope (english)Android Lab Test : Using the sensor gyroscope (english)
Android Lab Test : Using the sensor gyroscope (english)
 
Meteoio Introduction given by Mathias Bavey in Bozen
Meteoio Introduction given by Mathias Bavey in BozenMeteoio Introduction given by Mathias Bavey in Bozen
Meteoio Introduction given by Mathias Bavey in Bozen
 
How to become an Android dev starting from iOS (and vice versa)
How to become an Android dev starting from iOS (and vice versa)How to become an Android dev starting from iOS (and vice versa)
How to become an Android dev starting from iOS (and vice versa)
 
Chapter 6 - Process Synchronization
Chapter 6 - Process SynchronizationChapter 6 - Process Synchronization
Chapter 6 - Process Synchronization
 
Data binding in AngularJS, from model to view
Data binding in AngularJS, from model to viewData binding in AngularJS, from model to view
Data binding in AngularJS, from model to view
 
Writing SOLID C++ [gbgcpp meetup @ Zenseact]
Writing SOLID C++ [gbgcpp meetup @ Zenseact]Writing SOLID C++ [gbgcpp meetup @ Zenseact]
Writing SOLID C++ [gbgcpp meetup @ Zenseact]
 
LiveData on Steroids - Giora Shevach + Shahar Ben Moshe, Climacell
LiveData on Steroids - Giora Shevach + Shahar Ben Moshe, ClimacellLiveData on Steroids - Giora Shevach + Shahar Ben Moshe, Climacell
LiveData on Steroids - Giora Shevach + Shahar Ben Moshe, Climacell
 

Dernier

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 

Observer Pattern

  • 2. Weather Monitoring Application Weather Data Object Weather Station Guy that tracks the data Device that receives the coming from weather weather data station and updates the display Display Shows the current weather conditions.
  • 3. Job description Create an application that uses the weather data Object to update the three displays for weather conditions. The three displays are current conditions, weather stats and forecast
  • 4. Weather Data Class • getTemprature() • getPressure() • getHumidity() • measurementChanged() Weather Data Class
  • 5. Our Task Implement measurementchanged() function so that it updates the displays accordingly
  • 6. Simple Solution measurementChanged() { • Float temp = getTemperature(); • Float Pr= getPressure(); • Float Hum = getHumidity(); • currentConditionsDisplay.update(temp,Pr,Hum); • statisticsDisplay.update(temp,Pr,Hum); • forecastDisplay.update(temp,Pr,Hum);
  • 7. Problems with the previous approach We are coding to concrete implementation rather then to an interface. We have not encapsulated the part that changes from the part that remains constant. (Display Changes) We have no way to add or remove the weather displays at run time. If we want to add new display we have to alter code.
  • 8. The Observer Pattern Similar to Newspaper subscription. Publishers publish and subscribers read. Once subscribers unsubscribe publishers wont get anything to read. Once subscribers subscribe again they get to read. Publishers are Subject and subscribers are Observer. “The Observer pattern defines a one to many relationship between a set of objects. When the state of one changes it is notified to all the others.”
  • 9. Design: Class Diagram <<interface Subject>> <<interface Observer>> <<interface Display>> Removesubscriber() update() disp() addSubscriber() notifyObservers() CurrentConditionDisp StatisticsDisplay WeatherData Update(); Update(); addSubscriber() disp(); disp(); removerSubscriber() notifyObservers() measurementChanged() ForecastDisplay getTemprature() getHumidity() Update(); getPressure() disp();
  • 10. Implementation (Subject) public class WeatherData implements Subject{ private ArrayList Observers; private float temp,press,hum; public WeatherData() { Observers = new ArrayList();} Publc void removeObserver(Observer o) { int index = Observers.indexOf(o); Observers.remove(i); } Public void notifyObservers() { for(I =0;i<Observers.length();i++) { Observer o = (Observer)Observers.get(i); o.update(temp,hum,press); } } Public void measurementChanged() { notifyObservers(); } public void addObserver(Observer o) {Observers.add(o);}
  • 11. Implementation (Observer) public class CurrentConditionsDisplay implements Observer,Display { private float temp,hum,press; private Subject weatherData; public CurrentConditionsDisplay (Subject s){ this.weatherData = s; weatherData.addObserver(this); } Public void update(float temp, float press, float hum) { this.temp= temp; this. Press = press; display(); } public void display() { System.out.println(“ The current conditions of temperature are good : “+temp); }
  • 12. Java has built in support for Observer • You don’t have to implement the addObserver, removeObserver etc since these are already implemented in Observable class (not an interface). • Both are present in the java.util package. • You can also implement either pull or push style to your observers. • For an object to become Observer: – Implement the Observer Interface and call addObserver() on any Observable Object.
  • 13. Cont… • For the Observable to send notifications: – You must first call the protected setChanged() method to signify that the state has changed. – Then call one of the two notifyObservers() methos • notifyObservers() • notifyObservers(Object arg) – The argument passed is the data Obect. – For an Observer • Update(Observable o, Object arg) – Implements the update method. If you want the push model you can put the data in the dataObject else in case of pull method the Observer can get the data when ever it wants.
  • 14. Dark Side of Observer Java Built in Pattern • The Observable is a class not an interface. Any already defined class which has already extended a class can not subclass it. • You cant create your own implementation that plays well with Java Built in Observer API. • Observable protects the setChanged() method hence any class has to subclass It if they want to use Observable. This hampers the design principle “favor composite over inheritance” • Swing uses the Observer Pattern. Since every button has a number of listeners. Listeners are observers which wait for any change in the state of the button and respond accordingly.
  • 15. References… • Head First Design Patterns