SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

Strategy Pattern
Strategy PatternStrategy Pattern
Strategy Pattern
Guo Albert
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern
11prasoon
 

Was ist angesagt? (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
 

Andere mochten auch

Design patterns 4 - observer pattern
Design patterns   4 - observer patternDesign patterns   4 - observer pattern
Design patterns 4 - observer pattern
pixelblend
 
Observer Pattern Khali Young 2006 Aug
Observer Pattern Khali Young 2006 AugObserver Pattern Khali Young 2006 Aug
Observer Pattern Khali Young 2006 Aug
melbournepatterns
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
soms_1
 
Konstantin slisenko - Design patterns
Konstantin slisenko - Design patternsKonstantin slisenko - Design patterns
Konstantin slisenko - Design patterns
beloslab
 
Observer Pattern
Observer PatternObserver Pattern
Observer Pattern
Guo Albert
 

Andere mochten auch (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
 

Ähnlich wie Observer design pattern

Design patterns
Design patternsDesign patterns
Design patterns
ISsoft
 
Observer dp
Observer dpObserver dp
Observer dp
ISsoft
 

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

Kürzlich hochgeladen

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
PECB
 
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
kauryashika82
 

Kürzlich hochgeladen (20)

ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
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
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
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
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
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
 
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
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
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
 

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