SlideShare una empresa de Scribd logo
1 de 18
Research week #2
   Introduction
   Intent
   Class diagram
   Sequence diagram
   Benefit
   Implementations Issues
   Observer pattern in java
   Observer design pattern is behavioral pattern
   Used to assure consistency between objects.
   Separation of the objects that is dependent
    on each other.
   It used to make relation between objects at
    run time not compile time.
   Used in MVC(mainly Model & GUI part)
   Define a one-to-many dependency between
    objects so that when one object changes
    state, all its dependents are notified and
    updated automatically.
   Object that changes called “Subject”.

   Object that receives updates called “Object”.
   Sequence diagram

      observer                  Subject
                 Register/att
                     ach

                                Change state
                                   trigger
                  notify()/upda
                                 notification
                        te
                   getstate()
   Minimal coupling between the Subject and
    the Observer:
    Can reuse subjects without reusing their observers
     and vice versa.
    Observers can be added without modifying the
     subject.
    All subject knows is its list of observers so make
     decoupling.
    Subject does not need to know the concrete class of
     an observer.
   How does the subject keep track of its observers?
        Array, linked list, Vector

   What if an observer wants to observe more than
    one subject?
       subject tell the observer who it is via the update
    interface.

   Who triggers the update?
       The subject whenever its state changes.

   Can an observer also be a subject?
      Yes! Because class can implement more than
    one interface.
   How does Subject send the changed data to
    Object?

      Two ways:

       1-Pull model: Observer invoke method
    requesting data
         SubjectName.getdata();

       2-Push model: Subject passes data to
    observer as argument at update ()
        Object[i].update(SubjectName,data);
   We could implement the Observer pattern
    from scratch in Java.
   But Java provides the Observable/Observer
    classes as built-in support for the Observer
    pattern.
   The java.util.Observable class is the base
    Subject class. Any class that wants to be
    observed extends this class.
     Provides methods to add/delete observers
     Provides methods to notify all observers
     Uses a Vector for storing the observer references
   The java.util.Observer interface is the
    Observer interface. It must be implemented
    by any observer class.

   Java.util.Observable class
    public synchronized void addObserver(Observer o)
    public synchronized void deleteObserver(Observer
     o)
    protected synchronized void setChanged()
    public void notifyObservers()
    public void notifyObservers(Object arg)
   Java.util.Observer interface
    • public abstract void update(Observable o, Object
      arg)

   Let’s see sample code:
import java.util.Observable;
import java.util.Observer;
public class ConcreteSubject extends Observable {
  private String name;
  private float price;
  public ConcreteSubject(String name, float price) {
   this.name = name;
    this.price = price;
    System.out.println("ConcreteSubject created: " + name + " at "
       + price);
     }
  public String getName() {return name;}
  public float getPrice() {return price;}
  public void setPrice(float price) {
   this.price = price;
   setChanged();
     notifyObservers(new Float(price));
    }
}
import java .util.Observer;
import java .util.Observable;

public class ConcreteObserver implements Observer {
  private float price;
  public void NameObserver() {
    price =0;
   System.out.println("price observer is created is"+price);
}

    public void update(Observable obj, Object a) {

        price = ((Float)a).floatValue();
        System.out.println("PriceObserver: Price changed to " +
    price);
    }

}
public class TestObserver {

    /**
      * @param args
      */
    public static void main(String[] args) {
     ConcreteSubject s = new ConcreteSubject("GUI
    team",1.29f);
     ConcreteObserver o = new ConcreteObserver();
     s.addObserver(o);
     s.setPrice(4.56f);
     s.setPrice(2.3f);
    }

}
   Program output

ConcreteSubject created: GUI team at 1.29
PriceObserver: Price changed to 4.56
PriceObserver: Price changed to 2.3
   http://www.cs.clemson.edu/~malloy/courses
    /patterns/observer.html
   http://www.wohnklo.de/patterns/observer.ht
    ml
   http://msdn.microsoft.com/en-
    us/library/ee817669.aspx
   http://userpages.umbc.edu/~tarr/dp/lecture
    s/Observer.pdf

Más contenido relacionado

La actualidad más candente (20)

Strategy Pattern
Strategy PatternStrategy Pattern
Strategy Pattern
 
Model view controller (mvc)
Model view controller (mvc)Model view controller (mvc)
Model view controller (mvc)
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design Pattern
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design Pattern
 
Memento pattern
Memento patternMemento pattern
Memento pattern
 
Model View Controller (MVC)
Model View Controller (MVC)Model View Controller (MVC)
Model View Controller (MVC)
 
Servlets
ServletsServlets
Servlets
 
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
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Command and Adapter Pattern
Command and Adapter PatternCommand and Adapter Pattern
Command and Adapter Pattern
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
DESIGN PATTERNS: Strategy Patterns
DESIGN PATTERNS: Strategy PatternsDESIGN PATTERNS: Strategy Patterns
DESIGN PATTERNS: Strategy Patterns
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
 
Recycler view
Recycler viewRecycler view
Recycler view
 
Delegates and events in C#
Delegates and events in C#Delegates and events in C#
Delegates and events in C#
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Mvc architecture
Mvc architectureMvc architecture
Mvc architecture
 
Proxy pattern
Proxy patternProxy pattern
Proxy pattern
 

Destacado

Observer design pattern
Observer design patternObserver design pattern
Observer design patternSameer Rathoud
 
Design patterns 4 - observer pattern
Design patterns   4 - observer patternDesign patterns   4 - observer pattern
Design patterns 4 - observer patternpixelblend
 
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 pattern - Software Engineering
Design pattern - Software EngineeringDesign pattern - Software Engineering
Design pattern - Software EngineeringNadimozzaman Pappo
 
Design Patterns
Design PatternsDesign Patterns
Design Patternssoms_1
 
Konstantin slisenko - Design patterns
Konstantin slisenko - Design patternsKonstantin slisenko - Design patterns
Konstantin slisenko - Design patternsbeloslab
 
The Decorator Pattern
The Decorator PatternThe Decorator Pattern
The Decorator PatternAkshat Vig
 
Observer Pattern
Observer PatternObserver Pattern
Observer PatternGuo Albert
 
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
 
Design Pattern - 2. Observer
Design Pattern -  2. ObserverDesign Pattern -  2. Observer
Design Pattern - 2. ObserverFrancesco Ierna
 

Destacado (17)

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
 
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
 
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 pattern - Software Engineering
Design pattern - Software EngineeringDesign pattern - Software Engineering
Design pattern - Software Engineering
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
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
 
The Decorator Pattern
The Decorator PatternThe Decorator Pattern
The Decorator Pattern
 
Observer Pattern
Observer PatternObserver Pattern
Observer Pattern
 
Js design patterns
Js design patternsJs design patterns
Js design patterns
 
The Observer Pattern (Definition using UML)
The Observer Pattern (Definition using UML)The Observer Pattern (Definition using UML)
The Observer Pattern (Definition using UML)
 
Design Pattern - 2. Observer
Design Pattern -  2. ObserverDesign Pattern -  2. Observer
Design Pattern - 2. Observer
 

Similar a Observer design pattern

Design patterns
Design patternsDesign patterns
Design patternsISsoft
 
Observer pattern
Observer patternObserver pattern
Observer patternanshu_atri
 
Observer dp
Observer dpObserver dp
Observer dpISsoft
 
Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroidSavvycom Savvycom
 
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
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptFu Cheng
 
Java design patterns
Java design patternsJava design patterns
Java design patternsShawn Brito
 
Knockoutjs Part 2 Beginners
Knockoutjs Part 2 BeginnersKnockoutjs Part 2 Beginners
Knockoutjs Part 2 BeginnersBhaumik Patel
 
Scope.js prsentation
Scope.js prsentationScope.js prsentation
Scope.js prsentationAtishay Baid
 
Distributing information on iOS
Distributing information on iOSDistributing information on iOS
Distributing information on iOSMake School
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsMohammad Shaker
 
How To Utilize Context API With Class And Functional Componen in React.pptx
How To Utilize Context API With Class And Functional Componen in React.pptxHow To Utilize Context API With Class And Functional Componen in React.pptx
How To Utilize Context API With Class And Functional Componen in React.pptxBOSC Tech Labs
 
Reactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaReactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaNexThoughts Technologies
 

Similar a Observer design pattern (20)

Observer pattern
Observer patternObserver pattern
Observer pattern
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
33071-AOOP-Exp6 (2).pdf
33071-AOOP-Exp6 (2).pdf33071-AOOP-Exp6 (2).pdf
33071-AOOP-Exp6 (2).pdf
 
Observer dp
Observer dpObserver dp
Observer dp
 
Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroid
 
Rxandroid
RxandroidRxandroid
Rxandroid
 
RxAndroid
RxAndroidRxAndroid
RxAndroid
 
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
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
RxJava@Android
RxJava@AndroidRxJava@Android
RxJava@Android
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
 
Knockoutjs Part 2 Beginners
Knockoutjs Part 2 BeginnersKnockoutjs Part 2 Beginners
Knockoutjs Part 2 Beginners
 
Scope.js prsentation
Scope.js prsentationScope.js prsentation
Scope.js prsentation
 
EMF Tips n Tricks
EMF Tips n TricksEMF Tips n Tricks
EMF Tips n Tricks
 
Distributing information on iOS
Distributing information on iOSDistributing information on iOS
Distributing information on iOS
 
Sdp
SdpSdp
Sdp
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design Patterns
 
How To Utilize Context API With Class And Functional Componen in React.pptx
How To Utilize Context API With Class And Functional Componen in React.pptxHow To Utilize Context API With Class And Functional Componen in React.pptx
How To Utilize Context API With Class And Functional Componen in React.pptx
 
Reactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaReactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJava
 

Último

Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Shubhangi Sonawane
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterMateoGardella
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 

Último (20)

Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 

Observer design pattern

  • 2. Introduction  Intent  Class diagram  Sequence diagram  Benefit  Implementations Issues  Observer pattern in java
  • 3. Observer design pattern is behavioral pattern  Used to assure consistency between objects.  Separation of the objects that is dependent on each other.  It used to make relation between objects at run time not compile time.  Used in MVC(mainly Model & GUI part)
  • 4. Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.  Object that changes called “Subject”.  Object that receives updates called “Object”.
  • 5.
  • 6.
  • 7. Sequence diagram observer Subject Register/att ach Change state trigger notify()/upda notification te getstate()
  • 8. Minimal coupling between the Subject and the Observer: Can reuse subjects without reusing their observers and vice versa. Observers can be added without modifying the subject. All subject knows is its list of observers so make decoupling. Subject does not need to know the concrete class of an observer.
  • 9. How does the subject keep track of its observers? Array, linked list, Vector  What if an observer wants to observe more than one subject? subject tell the observer who it is via the update interface.  Who triggers the update? The subject whenever its state changes.  Can an observer also be a subject? Yes! Because class can implement more than one interface.
  • 10. How does Subject send the changed data to Object? Two ways: 1-Pull model: Observer invoke method requesting data SubjectName.getdata(); 2-Push model: Subject passes data to observer as argument at update () Object[i].update(SubjectName,data);
  • 11. We could implement the Observer pattern from scratch in Java.  But Java provides the Observable/Observer classes as built-in support for the Observer pattern.  The java.util.Observable class is the base Subject class. Any class that wants to be observed extends this class. Provides methods to add/delete observers Provides methods to notify all observers Uses a Vector for storing the observer references
  • 12. The java.util.Observer interface is the Observer interface. It must be implemented by any observer class.  Java.util.Observable class public synchronized void addObserver(Observer o) public synchronized void deleteObserver(Observer o) protected synchronized void setChanged() public void notifyObservers() public void notifyObservers(Object arg)
  • 13. Java.util.Observer interface • public abstract void update(Observable o, Object arg)  Let’s see sample code:
  • 14. import java.util.Observable; import java.util.Observer; public class ConcreteSubject extends Observable { private String name; private float price; public ConcreteSubject(String name, float price) { this.name = name; this.price = price; System.out.println("ConcreteSubject created: " + name + " at " + price); } public String getName() {return name;} public float getPrice() {return price;} public void setPrice(float price) { this.price = price; setChanged(); notifyObservers(new Float(price)); } }
  • 15. import java .util.Observer; import java .util.Observable; public class ConcreteObserver implements Observer { private float price; public void NameObserver() { price =0; System.out.println("price observer is created is"+price); } public void update(Observable obj, Object a) { price = ((Float)a).floatValue(); System.out.println("PriceObserver: Price changed to " + price); } }
  • 16. public class TestObserver { /** * @param args */ public static void main(String[] args) { ConcreteSubject s = new ConcreteSubject("GUI team",1.29f); ConcreteObserver o = new ConcreteObserver(); s.addObserver(o); s.setPrice(4.56f); s.setPrice(2.3f); } }
  • 17. Program output ConcreteSubject created: GUI team at 1.29 PriceObserver: Price changed to 4.56 PriceObserver: Price changed to 2.3
  • 18. http://www.cs.clemson.edu/~malloy/courses /patterns/observer.html  http://www.wohnklo.de/patterns/observer.ht ml  http://msdn.microsoft.com/en- us/library/ee817669.aspx  http://userpages.umbc.edu/~tarr/dp/lecture s/Observer.pdf