SlideShare ist ein Scribd-Unternehmen logo
1 von 16
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Command and Adapter Pattern
Command and Adapter PatternCommand and Adapter Pattern
Command and Adapter PatternJonathan Simon
 
Visitor Pattern
Visitor PatternVisitor Pattern
Visitor PatternIder Zheng
 
Chain of responsibility
Chain of responsibilityChain of responsibility
Chain of responsibilityShakil Ahmed
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design PatternVarun Arora
 
Dependency injection for beginners
Dependency injection for beginnersDependency injection for beginners
Dependency injection for beginnersBhushan Mulmule
 
Model view controller (mvc)
Model view controller (mvc)Model view controller (mvc)
Model view controller (mvc)M Ahsan Khan
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern PresentationJAINIK PATEL
 
What is Dependency Injection in Spring Boot | Edureka
What is Dependency Injection in Spring Boot | EdurekaWhat is Dependency Injection in Spring Boot | Edureka
What is Dependency Injection in Spring Boot | EdurekaEdureka!
 
A Brief Introduction to React.js
A Brief Introduction to React.jsA Brief Introduction to React.js
A Brief Introduction to React.jsDoug Neiner
 
Android Navigation Component
Android Navigation ComponentAndroid Navigation Component
Android Navigation ComponentŁukasz Ciupa
 

Was ist angesagt? (20)

Command Pattern
Command PatternCommand Pattern
Command Pattern
 
Command and Adapter Pattern
Command and Adapter PatternCommand and Adapter Pattern
Command and Adapter Pattern
 
Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Pattern
 
Visitor Pattern
Visitor PatternVisitor Pattern
Visitor Pattern
 
Proxy design pattern
Proxy design patternProxy design pattern
Proxy design pattern
 
Chain of responsibility
Chain of responsibilityChain of responsibility
Chain of responsibility
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design Pattern
 
Dependency injection for beginners
Dependency injection for beginnersDependency injection for beginners
Dependency injection for beginners
 
Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
 
Proxy pattern
Proxy patternProxy pattern
Proxy pattern
 
Memento pattern
Memento patternMemento pattern
Memento pattern
 
Model view controller (mvc)
Model view controller (mvc)Model view controller (mvc)
Model view controller (mvc)
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern Presentation
 
What is Dependency Injection in Spring Boot | Edureka
What is Dependency Injection in Spring Boot | EdurekaWhat is Dependency Injection in Spring Boot | Edureka
What is Dependency Injection in Spring Boot | Edureka
 
A Brief Introduction to React.js
A Brief Introduction to React.jsA Brief Introduction to React.js
A Brief Introduction to React.js
 
Proxy Design Pattern
Proxy Design PatternProxy Design Pattern
Proxy Design Pattern
 
Java servlets
Java servletsJava servlets
Java servlets
 
Builder pattern
Builder patternBuilder pattern
Builder pattern
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
 
Android Navigation Component
Android Navigation ComponentAndroid Navigation Component
Android Navigation Component
 

Andere mochten auch

Observer design pattern
Observer design patternObserver design pattern
Observer design patternSameer Rathoud
 
Observer Pattern Khali Young 2006 Aug
Observer Pattern Khali Young 2006 AugObserver Pattern Khali Young 2006 Aug
Observer Pattern Khali Young 2006 Augmelbournepatterns
 
Design patterns: observer pattern
Design patterns: observer patternDesign patterns: observer pattern
Design patterns: observer patternJyaasa Technologies
 
Design patterns 4 - observer pattern
Design patterns   4 - observer patternDesign patterns   4 - observer pattern
Design patterns 4 - observer patternpixelblend
 
Design pattern - Software Engineering
Design pattern - Software EngineeringDesign pattern - Software Engineering
Design pattern - Software EngineeringNadimozzaman Pappo
 
Mediator Pattern
Mediator PatternMediator Pattern
Mediator PatternAnuj Pawar
 
Konstantin slisenko - Design patterns
Konstantin slisenko - Design patternsKonstantin slisenko - Design patterns
Konstantin slisenko - Design patternsbeloslab
 
Observer Pattern
Observer PatternObserver Pattern
Observer PatternGuo Albert
 
Design Pattern - 2. Observer
Design Pattern -  2. ObserverDesign Pattern -  2. Observer
Design Pattern - 2. ObserverFrancesco Ierna
 
Observer pattern, delegate, event, lambda expression
Observer pattern, delegate, event, lambda expressionObserver pattern, delegate, event, lambda expression
Observer pattern, delegate, event, lambda expressionLearningTech
 
The Observer Pattern (Definition using UML)
The Observer Pattern (Definition using UML)The Observer Pattern (Definition using UML)
The Observer Pattern (Definition using UML)John Ortiz
 

Andere mochten auch (18)

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
 
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)
 

Ähnlich wie Observer Pattern

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 JVMNetesh Kumar
 
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. LaukePatrick Lauke
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
ReactiveCocoa in Practice
ReactiveCocoa in PracticeReactiveCocoa in Practice
ReactiveCocoa in PracticeOutware Mobile
 
Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroidSavvycom Savvycom
 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 SlidesYarikS
 
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 2JollyRogers5
 
Demystifying Reactive Programming
Demystifying Reactive ProgrammingDemystifying Reactive Programming
Demystifying Reactive ProgrammingTom Bulatewicz, PhD
 
Reactive Extensions: classic Observer in .NET
Reactive Extensions: classic Observer in .NETReactive Extensions: classic Observer in .NET
Reactive Extensions: classic Observer in .NETEPAM
 
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)Bruno Delb
 
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 BozenRiccardo Rigon
 
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)Giuseppe Filograno
 
Chapter 6 - Process Synchronization
Chapter 6 - Process SynchronizationChapter 6 - Process Synchronization
Chapter 6 - Process SynchronizationWayne Jones Jnr
 
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 viewThomas Roch
 
Writing SOLID C++ [gbgcpp meetup @ Zenseact]
Writing SOLID C++ [gbgcpp meetup @ Zenseact]Writing SOLID C++ [gbgcpp meetup @ Zenseact]
Writing SOLID C++ [gbgcpp meetup @ Zenseact]Dimitrios Platis
 
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, ClimacellDroidConTLV
 

Ähnlich wie 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
 

Kürzlich hochgeladen

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
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 FMESafe Software
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
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...DianaGray10
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
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 educationjfdjdjcjdnsjd
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
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...apidays
 
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 TerraformAndrey Devyatkin
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 

Kürzlich hochgeladen (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
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
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
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...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
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
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
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...
 
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
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 

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