SlideShare a Scribd company logo
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

More Related Content

What's hot

Proxy Design Pattern
Proxy Design PatternProxy Design Pattern
Proxy Design Pattern
Anjan Kumar Bollam
 
Decorator Design Pattern
Decorator Design PatternDecorator Design Pattern
Decorator Design Pattern
Adeel Riaz
 
Design patterns
Design patternsDesign patterns
Design patterns
abhisheksagi
 
Composite pattern
Composite patternComposite pattern
Composite pattern
Shakil Ahmed
 
Inversion of Control and Dependency Injection
Inversion of Control and Dependency InjectionInversion of Control and Dependency Injection
Inversion of Control and Dependency Injection
Dinesh Sharma
 
Structural Design pattern - Adapter
Structural Design pattern - AdapterStructural Design pattern - Adapter
Structural Design pattern - AdapterManoj Kumar
 
The State Design Pattern
The State Design PatternThe State Design Pattern
The State Design Pattern
Josh Candish
 
Command Pattern
Command PatternCommand Pattern
Command Pattern
Geoff Burns
 
Design Pattern - MVC, MVP and MVVM
Design Pattern - MVC, MVP and MVVMDesign Pattern - MVC, MVP and MVVM
Design Pattern - MVC, MVP and MVVM
Mudasir Qazi
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design Pattern
Shahriar Hyder
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
melbournepatterns
 
Architecting iOS Project
Architecting iOS ProjectArchitecting iOS Project
Architecting iOS Project
Massimo Oliviero
 
Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Pattern
Anjan Kumar Bollam
 
Design patterns in android
Design patterns in androidDesign patterns in android
Design patterns in android
Zahra Heydari
 
Proxy design pattern
Proxy design patternProxy design pattern
Proxy design pattern
Sase Kleckovski
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
Thibaud Desodt
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design Pattern
Sanae BEKKAR
 
Model view controller (mvc)
Model view controller (mvc)Model view controller (mvc)
Model view controller (mvc)
M Ahsan Khan
 

What's hot (20)

Proxy Design Pattern
Proxy Design PatternProxy Design Pattern
Proxy Design Pattern
 
Decorator Design Pattern
Decorator Design PatternDecorator Design Pattern
Decorator Design Pattern
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Composite pattern
Composite patternComposite pattern
Composite pattern
 
Inversion of Control and Dependency Injection
Inversion of Control and Dependency InjectionInversion of Control and Dependency Injection
Inversion of Control and Dependency Injection
 
Structural Design pattern - Adapter
Structural Design pattern - AdapterStructural Design pattern - Adapter
Structural Design pattern - Adapter
 
The State Design Pattern
The State Design PatternThe State Design Pattern
The State Design Pattern
 
Design patterns tutorials
Design patterns tutorialsDesign patterns tutorials
Design patterns tutorials
 
Command Pattern
Command PatternCommand Pattern
Command Pattern
 
Design Pattern - MVC, MVP and MVVM
Design Pattern - MVC, MVP and MVVMDesign Pattern - MVC, MVP and MVVM
Design Pattern - MVC, MVP and MVVM
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design Pattern
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
 
Architecting iOS Project
Architecting iOS ProjectArchitecting iOS Project
Architecting iOS Project
 
Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Pattern
 
Design patterns in android
Design patterns in androidDesign patterns in android
Design patterns in android
 
Proxy design pattern
Proxy design patternProxy design pattern
Proxy design pattern
 
Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design Pattern
 
Model view controller (mvc)
Model view controller (mvc)Model view controller (mvc)
Model view controller (mvc)
 

Viewers also liked

Observer design pattern
Observer design patternObserver design pattern
Observer design pattern
Yenifer Castrillon
 
Observer design pattern
Observer design patternObserver design pattern
Observer design pattern
Sameer 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 pattern
Jyaasa Technologies
 
Design patterns 4 - observer pattern
Design patterns   4 - observer patternDesign patterns   4 - observer pattern
Design patterns 4 - observer patternpixelblend
 
Observer pattern
Observer patternObserver pattern
Observer pattern
Shahriar Iqbal Chowdhury
 
Design pattern - Software Engineering
Design pattern - Software EngineeringDesign pattern - Software Engineering
Design pattern - Software Engineering
Nadimozzaman Pappo
 
Mediator Pattern
Mediator PatternMediator Pattern
Mediator PatternAnuj Pawar
 
Memento pattern
Memento patternMemento pattern
Memento pattern
Sayanton Vhaduri
 
Mediator pattern
Mediator patternMediator pattern
Mediator pattern
Shakil Ahmed
 
Mediator Design Pattern
Mediator Design PatternMediator Design Pattern
Mediator Design Pattern
Kuyseng Chhoeun
 
Konstantin slisenko - Design patterns
Konstantin slisenko - Design patternsKonstantin slisenko - Design patterns
Konstantin slisenko - Design patternsbeloslab
 
L05 Design Patterns
L05 Design PatternsL05 Design Patterns
L05 Design Patterns
Ólafur Andri Ragnarsson
 
Observer Pattern
Observer PatternObserver Pattern
Observer PatternGuo Albert
 
Design Pattern - 2. Observer
Design Pattern -  2. ObserverDesign Pattern -  2. Observer
Design Pattern - 2. Observer
Francesco 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
 

Viewers also liked (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)
 

Similar to 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 JVM
Netesh Kumar
 
Saving lives with rx java
Saving lives with rx javaSaving lives with rx java
Saving lives with rx java
Shahar Barsheshet
 
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
Patrick Lauke
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
Rick Warren
 
ReactiveCocoa in Practice
ReactiveCocoa in PracticeReactiveCocoa in Practice
ReactiveCocoa in Practice
Outware Mobile
 
Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroid
Savvycom Savvycom
 
Rxandroid
RxandroidRxandroid
Rxandroid
Thinh Thanh
 
RxAndroid
RxAndroidRxAndroid
RxAndroid
Thinh Thanh
 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 Slides
YarikS
 
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
JollyRogers5
 
RxJava@Android
RxJava@AndroidRxJava@Android
RxJava@Android
Maxim Volgin
 
Demystifying Reactive Programming
Demystifying Reactive ProgrammingDemystifying Reactive Programming
Demystifying Reactive Programming
Tom Bulatewicz, PhD
 
Reactive Extensions: classic Observer in .NET
Reactive Extensions: classic Observer in .NETReactive Extensions: classic Observer in .NET
Reactive Extensions: classic Observer in .NET
EPAM
 
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 Bozen
Riccardo 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 view
Thomas 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, Climacell
DroidConTLV
 

Similar to 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
 

Recently uploaded

Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 

Recently uploaded (20)

Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.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