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?

Chain of responsibility
Chain of responsibilityChain of responsibility
Chain of responsibilityShakil Ahmed
 
Observer and Decorator Pattern
Observer and Decorator PatternObserver and Decorator Pattern
Observer and Decorator PatternJonathan Simon
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API07.pallav
 
Design Patterns - General Introduction
Design Patterns - General IntroductionDesign Patterns - General Introduction
Design Patterns - General IntroductionAsma CHERIF
 
Padrão de Projeto Observer
Padrão de Projeto ObserverPadrão de Projeto Observer
Padrão de Projeto ObserverLuiza Uira
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern PresentationJAINIK PATEL
 
Design Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternDesign Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternMudasir Qazi
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern11prasoon
 
Android activity lifecycle
Android activity lifecycleAndroid activity lifecycle
Android activity lifecycleSoham Patel
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency InjectionKnoldus Inc.
 
Angular Dependency Injection
Angular Dependency InjectionAngular Dependency Injection
Angular Dependency InjectionNir Kaufman
 

Was ist angesagt? (20)

Chain of responsibility
Chain of responsibilityChain of responsibility
Chain of responsibility
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Observer and Decorator Pattern
Observer and Decorator PatternObserver and Decorator Pattern
Observer and Decorator Pattern
 
Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
 
Command Pattern
Command PatternCommand Pattern
Command Pattern
 
ADO.NET
ADO.NETADO.NET
ADO.NET
 
Memento pattern
Memento patternMemento pattern
Memento pattern
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Design Patterns - General Introduction
Design Patterns - General IntroductionDesign Patterns - General Introduction
Design Patterns - General Introduction
 
Padrão de Projeto Observer
Padrão de Projeto ObserverPadrão de Projeto Observer
Padrão de Projeto Observer
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern Presentation
 
Design Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternDesign Pattern - Factory Method Pattern
Design Pattern - Factory Method Pattern
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern
 
Android activity lifecycle
Android activity lifecycleAndroid activity lifecycle
Android activity lifecycle
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Recycler view
Recycler viewRecycler view
Recycler view
 
ADO .Net
ADO .Net ADO .Net
ADO .Net
 
Angular Directives
Angular DirectivesAngular Directives
Angular Directives
 
Angular Dependency Injection
Angular Dependency InjectionAngular Dependency Injection
Angular Dependency Injection
 
Decorator Pattern
Decorator PatternDecorator Pattern
Decorator Pattern
 

Andere mochten auch

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
 
Strategy Pattern
Strategy PatternStrategy Pattern
Strategy 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
 

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
 
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
 
Strategy Pattern
Strategy PatternStrategy Pattern
Strategy Pattern
 
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 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
 

Ä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

Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
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
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
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.pptxMaritesTamaniVerdade
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
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.christianmathematics
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
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...Poonam Aher Patil
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 

Kürzlich hochgeladen (20)

Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
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
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
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
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.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.
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
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...
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 

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