SlideShare a Scribd company logo
Observer Pattern in Java
by
Somenath Mukhopadhyay
som-itsolutions
As i was going through the different source code files of the Java Util package, i found the
implementation of the Observer Pattern ( see the Gang of Four book for more
information on this pattern) in the two places - namely Observer.java and
Observable.java. i would like to throw some lights on these two classes. These two
classes can be found in the Javaj2sesrcshareclassesjavautil folder of the
JDK source code.
But first of all, i need to give you a practical example of why we need observer pattern in the
first place.
Suppose, we have a document which can be viewed simultaneously by three different views
– say one view represnts a line graph chart, another view represents it in a spreadsheet, yet
another view represnts a pie chart. Now suppose the spreadsheet view makes some
modification to the document. If the other two views don't update themselves with this
changed state of the document, different views will be in inconsistent states. So we need
some mechanism to notify the other two views whenever the spreadsheet view updates the
document. This is done through Observer pattern in which whenever the document changes
stete, it notifies all of its views. The views in turn updates themselves with the latest data.
Fig 1: Class Diagram of Observer Pattern
Fig 2: Sequence Diagram of Observer Pattern
What these two diagrams essentially depict is that in the Observer Pattern, we have a
Subject, which can attach one or more Observers through its Attach() function. Whenever it
changes its state it Notifies all the attached Observers through its notify function. The
observers in turn synchronize their states with that of the Subject through the
GetSubjectState function.
So now let us first start with the Observable.java class. As the name suggests it is the class
which will implemented functionalities for being observed. Or in other words it is the class
which helps in designing the Subject class of the Observer pattern discussion of the GoF
book. We need to extend this class to get the Subject class.
Let us try to dissect this class. The following functions are there in this class:
1. Data Members : It has a vector to hold all the observers that are
interested in observing this observable class. It has another boolean data
member called "changed" to indicate if anything has changed in the
Subject class ( which will be derived from this Observable class).
2. Constructor : This class has a no argument constructor to construct an
empty vector of Observers.
3. Member Functions :
 addObserver : To add an observer to its list of Observers.
 deleteObserver : To delete a particular observer from the list of
the observers
 notifyObservers : There are two overloaded versions of this
function. One takes an Object parameter as an argument and the other
does not take any argument. The task of this function is to notify all the
attached observers when any data of the subject gets changed. To check
whether the data is changed it evaluates the boolean "changed" data
member. This function also calls the update function of each observer objects
to ask them to get in sync with the subject's changed state. The overloaded
version that takes an one argument parameter is used to let the observers
know about which attribute is changed. And the other version of this function
which does not take any argument does not let the observer know about
which attribute is changed.
 deleteObservers : This function removes all the observers
attached to this subject.
 setChanged : This function sets the boolean data member
"changed".
 clearChanged : This function resets the boolean data member
"changed".
 hasChanged : This function helps us to know whether the data of
the subject has been changed or not.
 countObservers : This function returns the number of
observers attached to this subject.
This is all about the Observable class which helps us to define to Subject class.
The Observer.java defines an interface called Observer having just one abstract
function called update (Observable o, Object arg). As the name suggests, the
Observer class that will implement this interface will override the update function to set the
attribute passed as an argument (arg) from the Subject class. This method is called
whenever any attribute in the Subject class gets changed.
Now let us try to see an example to understand how this Observer Pattern is used. Let us
first extend the Observable class to create the Subject class.
package com.somitsolutions.training.java.observerpattern;
import java.util.Observable;
public class Subject extends Observable {
private String name;
private float price;
public Subject(String name, float price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public float getPrice() {
return price;
}
public void setName(String name) {
this.name = name;
setChanged();
notifyObservers(name);
}
public void setPrice(float price) {
this.price = price;
setChanged();
notifyObservers(new Float(price));
}
}
As this is clear from the implementation of the Subject class, that whenever we call the setter
function to change the attributes of the Subject's object, we call the notifyObservers and
pass that attribute as a parameter.
Now let us see how we create two different observers namely NameObserver and
PriceObserver to observe these two attributes of the Subject class.
// An observer of name changes.
package com.somitsolutions.training.java.observerpattern;
import java.util.Observable;
import java.util.Observer;
public class NameObserver implements Observer {
private String name;
public NameObserver() {
name = null;
System.out.println("NameObserver created: Name is " + name);
}
@Override
public void update(Observable o, Object arg) {
// TODO Auto-generated method stub
if (arg instanceof String) {
name = (String)arg;
System.out.println("NameObserver: Name changed to " + name);
}
}
}
// An observer of price changes.
package com.somitsolutions.training.java.observerpattern;
import java.util.Observable;
import java.util.Observer;
public class PriceObserver implements Observer {
private float price; public PriceObserver() {
price = 0;
System.out.println("PriceObserver created: Price is " + price);
}
@Override
public void update(Observable o, Object arg) {
// TODO Auto-generated method stub
if (arg instanceof Float) {
price = ((Float)arg).floatValue();
System.out.println("PriceObserver: Price changed to " + price);
}
}
}
As it has become clear from the above two implementations that the update function actually
helps in synchronizing the state of the concrete observers with that of the Subject.
Now the client of the Observer framework will look like the following :
package com.somitsolutions.training.java.observerpattern;
public class Main {
public static void main(String args[]) {
// Create the Subject and Observers.
Subject s = new Subject("Kheer Kadam", 20.5f);
NameObserver nameObs = new NameObserver();
PriceObserver priceObs = new PriceObserver();
// Add those Observers!
s.addObserver(nameObs);
s.addObserver(priceObs);
//Initial Subject States
System.out.println("Initial states of Subject");
System.out.println("Name : " + s.getName());
System.out.println("Price : " + Float.toString(s.getPrice()));
// Make changes to the Subject.
s.setName("Gulabjamun"); // It prints NameObserver: Name changed to
Gulabjamun
s.setPrice(15.0f); //It prints PriceObserver: Price changed to 15.0
s.setPrice(30.5f); //It prints PriceObserver: Price changed to 30.5
s.setName("Rasgulla"); // It prints NameObserver: Name changed to
Rasgulla
}
}
Hope the above discussion will help people understand of how the Java supports
implementing the Observer pattern.

More Related Content

What's hot

React hooks
React hooksReact hooks
React hooks
Assaf Gannon
 
Javascript closures
Javascript closures Javascript closures
Javascript closures
VNG
 
Java Unit 2(Part 1)
Java Unit 2(Part 1)Java Unit 2(Part 1)
Java Unit 2(Part 1)
SURBHI SAROHA
 
React hooks
React hooksReact hooks
React hooks
Sadhna Rana
 
Observer and Decorator Pattern
Observer and Decorator PatternObserver and Decorator Pattern
Observer and Decorator Pattern
Jonathan Simon
 
Art of unit testing: How developer should care about code quality
Art of unit testing: How developer should care about code qualityArt of unit testing: How developer should care about code quality
Art of unit testing: How developer should care about code quality
Dmytro Patserkovskyi
 
React new features and intro to Hooks
React new features and intro to HooksReact new features and intro to Hooks
React new features and intro to Hooks
Soluto
 
Build Widgets
Build WidgetsBuild Widgets
Build Widgets
scottw
 
Chapter 1 Presentation
Chapter 1 PresentationChapter 1 Presentation
Chapter 1 Presentation
guest0d6229
 
Java Queue.pptx
Java Queue.pptxJava Queue.pptx
Java Queue.pptx
vishal choudhary
 
Design Pattern - 2. Observer
Design Pattern -  2. ObserverDesign Pattern -  2. Observer
Design Pattern - 2. Observer
Francesco Ierna
 
React hooks beyond hype
React hooks beyond hypeReact hooks beyond hype
React hooks beyond hype
Magdiel Duarte
 
Java Stack Data Structure.pptx
Java Stack Data Structure.pptxJava Stack Data Structure.pptx
Java Stack Data Structure.pptx
vishal choudhary
 
React – Let’s “Hook” up
React – Let’s “Hook” upReact – Let’s “Hook” up
React – Let’s “Hook” up
InnovationM
 
13 advanced-swing
13 advanced-swing13 advanced-swing
13 advanced-swingNataraj Dg
 
ConsTRUCTION AND DESTRUCTION
ConsTRUCTION AND DESTRUCTIONConsTRUCTION AND DESTRUCTION
ConsTRUCTION AND DESTRUCTION
Shweta Shah
 
A fresh look at Java Enterprise Application testing with Arquillian
A fresh look at Java Enterprise Application testing with ArquillianA fresh look at Java Enterprise Application testing with Arquillian
A fresh look at Java Enterprise Application testing with Arquillian
Vineet Reynolds
 
Effective Java. By materials of Josch Bloch's book
Effective Java. By materials of Josch Bloch's bookEffective Java. By materials of Josch Bloch's book
Effective Java. By materials of Josch Bloch's book
Roman Tsypuk
 
Observer design pattern
Observer design patternObserver design pattern
Observer design patternSara Torkey
 
Knockoutjs Part 2 Beginners
Knockoutjs Part 2 BeginnersKnockoutjs Part 2 Beginners
Knockoutjs Part 2 Beginners
Bhaumik Patel
 

What's hot (20)

React hooks
React hooksReact hooks
React hooks
 
Javascript closures
Javascript closures Javascript closures
Javascript closures
 
Java Unit 2(Part 1)
Java Unit 2(Part 1)Java Unit 2(Part 1)
Java Unit 2(Part 1)
 
React hooks
React hooksReact hooks
React hooks
 
Observer and Decorator Pattern
Observer and Decorator PatternObserver and Decorator Pattern
Observer and Decorator Pattern
 
Art of unit testing: How developer should care about code quality
Art of unit testing: How developer should care about code qualityArt of unit testing: How developer should care about code quality
Art of unit testing: How developer should care about code quality
 
React new features and intro to Hooks
React new features and intro to HooksReact new features and intro to Hooks
React new features and intro to Hooks
 
Build Widgets
Build WidgetsBuild Widgets
Build Widgets
 
Chapter 1 Presentation
Chapter 1 PresentationChapter 1 Presentation
Chapter 1 Presentation
 
Java Queue.pptx
Java Queue.pptxJava Queue.pptx
Java Queue.pptx
 
Design Pattern - 2. Observer
Design Pattern -  2. ObserverDesign Pattern -  2. Observer
Design Pattern - 2. Observer
 
React hooks beyond hype
React hooks beyond hypeReact hooks beyond hype
React hooks beyond hype
 
Java Stack Data Structure.pptx
Java Stack Data Structure.pptxJava Stack Data Structure.pptx
Java Stack Data Structure.pptx
 
React – Let’s “Hook” up
React – Let’s “Hook” upReact – Let’s “Hook” up
React – Let’s “Hook” up
 
13 advanced-swing
13 advanced-swing13 advanced-swing
13 advanced-swing
 
ConsTRUCTION AND DESTRUCTION
ConsTRUCTION AND DESTRUCTIONConsTRUCTION AND DESTRUCTION
ConsTRUCTION AND DESTRUCTION
 
A fresh look at Java Enterprise Application testing with Arquillian
A fresh look at Java Enterprise Application testing with ArquillianA fresh look at Java Enterprise Application testing with Arquillian
A fresh look at Java Enterprise Application testing with Arquillian
 
Effective Java. By materials of Josch Bloch's book
Effective Java. By materials of Josch Bloch's bookEffective Java. By materials of Josch Bloch's book
Effective Java. By materials of Josch Bloch's book
 
Observer design pattern
Observer design patternObserver design pattern
Observer design pattern
 
Knockoutjs Part 2 Beginners
Knockoutjs Part 2 BeginnersKnockoutjs Part 2 Beginners
Knockoutjs Part 2 Beginners
 

Viewers also liked

Implementation of a state machine for a longrunning background task in androi...
Implementation of a state machine for a longrunning background task in androi...Implementation of a state machine for a longrunning background task in androi...
Implementation of a state machine for a longrunning background task in androi...
Somenath Mukhopadhyay
 
Structural Relationship between Content Resolver and Content Provider of Andr...
Structural Relationship between Content Resolver and Content Provider of Andr...Structural Relationship between Content Resolver and Content Provider of Andr...
Structural Relationship between Content Resolver and Content Provider of Andr...
Somenath Mukhopadhyay
 
Design patterns
Design patternsDesign patterns
Design patternsISsoft
 
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
 
Observer & singleton pattern
Observer  & singleton patternObserver  & singleton pattern
Observer & singleton patternbabak danyal
 
Design patterns: observer pattern
Design patterns: observer patternDesign patterns: observer pattern
Design patterns: observer pattern
Jyaasa Technologies
 
Observer pattern
Observer patternObserver pattern
Observer pattern
Shahriar Iqbal Chowdhury
 
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
 
Factory Pattern
Factory PatternFactory Pattern
Factory Pattern
Monjurul Habib
 
Design Patterns in Cocoa Touch
Design Patterns in Cocoa TouchDesign Patterns in Cocoa Touch
Design Patterns in Cocoa Touch
Eliah Nikans
 
Reflective portfolio
Reflective portfolioReflective portfolio
Reflective portfolio
jobbo1
 
Design Pattern - Observer Pattern
Design Pattern - Observer PatternDesign Pattern - Observer Pattern
Design Pattern - Observer Pattern
Mudasir Qazi
 
Observer Pattern
Observer PatternObserver Pattern
Observer Pattern
Akshat Vig
 
Observer pattern
Observer patternObserver pattern
Observer pattern
Samreen Farooq
 
Observer design pattern
Observer design patternObserver design pattern
Observer design pattern
Sameer Rathoud
 
Design pattern - Software Engineering
Design pattern - Software EngineeringDesign pattern - Software Engineering
Design pattern - Software Engineering
Nadimozzaman Pappo
 
Colombo Architecture Meetup - Enterprise Architectural Challenges in Large En...
Colombo Architecture Meetup - Enterprise Architectural Challenges in Large En...Colombo Architecture Meetup - Enterprise Architectural Challenges in Large En...
Colombo Architecture Meetup - Enterprise Architectural Challenges in Large En...Crishantha Nanayakkara
 

Viewers also liked (20)

Implementation of a state machine for a longrunning background task in androi...
Implementation of a state machine for a longrunning background task in androi...Implementation of a state machine for a longrunning background task in androi...
Implementation of a state machine for a longrunning background task in androi...
 
Structural Relationship between Content Resolver and Content Provider of Andr...
Structural Relationship between Content Resolver and Content Provider of Andr...Structural Relationship between Content Resolver and Content Provider of Andr...
Structural Relationship between Content Resolver and Content Provider of Andr...
 
Design patterns
Design patternsDesign patterns
Design patterns
 
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)
 
Observer & singleton pattern
Observer  & singleton patternObserver  & singleton pattern
Observer & singleton pattern
 
Design patterns: observer pattern
Design patterns: observer patternDesign patterns: observer pattern
Design patterns: observer pattern
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Design patterns 4 - observer pattern
Design patterns   4 - observer patternDesign patterns   4 - observer pattern
Design patterns 4 - 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
 
Factory Pattern
Factory PatternFactory Pattern
Factory Pattern
 
Design Patterns in Cocoa Touch
Design Patterns in Cocoa TouchDesign Patterns in Cocoa Touch
Design Patterns in Cocoa Touch
 
Reflective portfolio
Reflective portfolioReflective portfolio
Reflective portfolio
 
Design Pattern - Observer Pattern
Design Pattern - Observer PatternDesign Pattern - Observer Pattern
Design Pattern - Observer Pattern
 
Observer Pattern
Observer PatternObserver Pattern
Observer Pattern
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
Observer design pattern
Observer design patternObserver design pattern
Observer design pattern
 
Design pattern - Software Engineering
Design pattern - Software EngineeringDesign pattern - Software Engineering
Design pattern - Software Engineering
 
Colombo Architecture Meetup - Enterprise Architectural Challenges in Large En...
Colombo Architecture Meetup - Enterprise Architectural Challenges in Large En...Colombo Architecture Meetup - Enterprise Architectural Challenges in Large En...
Colombo Architecture Meetup - Enterprise Architectural Challenges in Large En...
 

Similar to Observer pattern

Chapter 8 java
Chapter 8 javaChapter 8 java
Chapter 8 java
Ahmad sohail Kakar
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
ssuser8347a1
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classes
Fajar Baskoro
 
Refactoring Chapter 6,7.pptx
Refactoring Chapter 6,7.pptxRefactoring Chapter 6,7.pptx
Refactoring Chapter 6,7.pptx
Eskişehir Technical University
 
Computer Programming 2
Computer Programming 2 Computer Programming 2
Computer Programming 2
VasanthiMuniasamy2
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
Fu Cheng
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
madhavi patil
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
chetanpatilcp783
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
Naga Muruga
 
Java Beans
Java BeansJava Beans
Java Beans
Ankit Desai
 
JavaScript OOPS Implimentation
JavaScript OOPS ImplimentationJavaScript OOPS Implimentation
JavaScript OOPS Implimentation
Usman Mehmood
 
Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ Comparator
Sean McElrath
 
Chapter 7 java
Chapter 7 javaChapter 7 java
Chapter 7 java
Ahmad sohail Kakar
 
Design patterns
Design patternsDesign patterns
Design patterns
Anas Alpure
 
Functional JavaScript Fundamentals
Functional JavaScript FundamentalsFunctional JavaScript Fundamentals
Functional JavaScript Fundamentals
Srdjan Strbanovic
 
Day 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViewsDay 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViewsAhsanul Karim
 
Scope.js prsentation
Scope.js prsentationScope.js prsentation
Scope.js prsentation
Atishay Baid
 
Observer pattern
Observer patternObserver pattern
Observer pattern
anshu_atri
 
React table tutorial use filter (part 2)
React table tutorial use filter (part 2)React table tutorial use filter (part 2)
React table tutorial use filter (part 2)
Katy Slemon
 

Similar to Observer pattern (20)

Chapter 8 java
Chapter 8 javaChapter 8 java
Chapter 8 java
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classes
 
Refactoring Chapter 6,7.pptx
Refactoring Chapter 6,7.pptxRefactoring Chapter 6,7.pptx
Refactoring Chapter 6,7.pptx
 
Computer Programming 2
Computer Programming 2 Computer Programming 2
Computer Programming 2
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Reflection
ReflectionReflection
Reflection
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
Java Beans
Java BeansJava Beans
Java Beans
 
JavaScript OOPS Implimentation
JavaScript OOPS ImplimentationJavaScript OOPS Implimentation
JavaScript OOPS Implimentation
 
Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ Comparator
 
Chapter 7 java
Chapter 7 javaChapter 7 java
Chapter 7 java
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Functional JavaScript Fundamentals
Functional JavaScript FundamentalsFunctional JavaScript Fundamentals
Functional JavaScript Fundamentals
 
Day 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViewsDay 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViews
 
Scope.js prsentation
Scope.js prsentationScope.js prsentation
Scope.js prsentation
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
React table tutorial use filter (part 2)
React table tutorial use filter (part 2)React table tutorial use filter (part 2)
React table tutorial use filter (part 2)
 

More from Somenath Mukhopadhyay

Significance of private inheritance in C++...
Significance of private inheritance in C++...Significance of private inheritance in C++...
Significance of private inheritance in C++...
Somenath Mukhopadhyay
 
Arranging the words of a text lexicographically trie
Arranging the words of a text lexicographically   trieArranging the words of a text lexicographically   trie
Arranging the words of a text lexicographically trie
Somenath Mukhopadhyay
 
Generic asynchronous HTTP utility for android
Generic asynchronous HTTP utility for androidGeneric asynchronous HTTP utility for android
Generic asynchronous HTTP utility for android
Somenath Mukhopadhyay
 
Copy on write
Copy on writeCopy on write
Copy on write
Somenath Mukhopadhyay
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future Task
Somenath Mukhopadhyay
 
Memory layout in C++ vis a-vis polymorphism and padding bits
Memory layout in C++ vis a-vis polymorphism and padding bitsMemory layout in C++ vis a-vis polymorphism and padding bits
Memory layout in C++ vis a-vis polymorphism and padding bits
Somenath Mukhopadhyay
 
Developing an Android REST client to determine POI using asynctask and integr...
Developing an Android REST client to determine POI using asynctask and integr...Developing an Android REST client to determine POI using asynctask and integr...
Developing an Android REST client to determine POI using asynctask and integr...
Somenath Mukhopadhyay
 
Uml training
Uml trainingUml training
Uml training
Somenath Mukhopadhyay
 
How to create your own background for google docs
How to create your own background for google docsHow to create your own background for google docs
How to create your own background for google docs
Somenath Mukhopadhyay
 
The Designing of a Software System from scratch with the help of OOAD & UML -...
The Designing of a Software System from scratch with the help of OOAD & UML -...The Designing of a Software System from scratch with the help of OOAD & UML -...
The Designing of a Software System from scratch with the help of OOAD & UML -...
Somenath Mukhopadhyay
 
Flow of events during Media Player creation in Android
Flow of events during Media Player creation in AndroidFlow of events during Media Player creation in Android
Flow of events during Media Player creation in Android
Somenath Mukhopadhyay
 
Tackling circular dependency in Java
Tackling circular dependency in JavaTackling circular dependency in Java
Tackling circular dependency in Java
Somenath Mukhopadhyay
 
Implementation of composite design pattern in android view and widgets
Implementation of composite design pattern in android view and widgetsImplementation of composite design pattern in android view and widgets
Implementation of composite design pattern in android view and widgets
Somenath Mukhopadhyay
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ Constructor
Somenath Mukhopadhyay
 
Active object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architectureActive object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architecture
Somenath Mukhopadhyay
 
Android services internals
Android services internalsAndroid services internals
Android services internals
Somenath Mukhopadhyay
 
Android Asynctask Internals vis-a-vis half-sync half-async design pattern
Android Asynctask Internals vis-a-vis half-sync half-async design patternAndroid Asynctask Internals vis-a-vis half-sync half-async design pattern
Android Asynctask Internals vis-a-vis half-sync half-async design pattern
Somenath Mukhopadhyay
 
Composite Pattern
Composite PatternComposite Pattern
Composite Pattern
Somenath Mukhopadhyay
 
Test Driven Development and JUnit
Test Driven Development and JUnitTest Driven Development and JUnit
Test Driven Development and JUnit
Somenath Mukhopadhyay
 

More from Somenath Mukhopadhyay (20)

Significance of private inheritance in C++...
Significance of private inheritance in C++...Significance of private inheritance in C++...
Significance of private inheritance in C++...
 
Arranging the words of a text lexicographically trie
Arranging the words of a text lexicographically   trieArranging the words of a text lexicographically   trie
Arranging the words of a text lexicographically trie
 
Generic asynchronous HTTP utility for android
Generic asynchronous HTTP utility for androidGeneric asynchronous HTTP utility for android
Generic asynchronous HTTP utility for android
 
Copy on write
Copy on writeCopy on write
Copy on write
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future Task
 
Memory layout in C++ vis a-vis polymorphism and padding bits
Memory layout in C++ vis a-vis polymorphism and padding bitsMemory layout in C++ vis a-vis polymorphism and padding bits
Memory layout in C++ vis a-vis polymorphism and padding bits
 
Developing an Android REST client to determine POI using asynctask and integr...
Developing an Android REST client to determine POI using asynctask and integr...Developing an Android REST client to determine POI using asynctask and integr...
Developing an Android REST client to determine POI using asynctask and integr...
 
Uml training
Uml trainingUml training
Uml training
 
How to create your own background for google docs
How to create your own background for google docsHow to create your own background for google docs
How to create your own background for google docs
 
The Designing of a Software System from scratch with the help of OOAD & UML -...
The Designing of a Software System from scratch with the help of OOAD & UML -...The Designing of a Software System from scratch with the help of OOAD & UML -...
The Designing of a Software System from scratch with the help of OOAD & UML -...
 
Flow of events during Media Player creation in Android
Flow of events during Media Player creation in AndroidFlow of events during Media Player creation in Android
Flow of events during Media Player creation in Android
 
Tackling circular dependency in Java
Tackling circular dependency in JavaTackling circular dependency in Java
Tackling circular dependency in Java
 
Implementation of composite design pattern in android view and widgets
Implementation of composite design pattern in android view and widgetsImplementation of composite design pattern in android view and widgets
Implementation of composite design pattern in android view and widgets
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ Constructor
 
Active object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architectureActive object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architecture
 
Android services internals
Android services internalsAndroid services internals
Android services internals
 
Android Asynctask Internals vis-a-vis half-sync half-async design pattern
Android Asynctask Internals vis-a-vis half-sync half-async design patternAndroid Asynctask Internals vis-a-vis half-sync half-async design pattern
Android Asynctask Internals vis-a-vis half-sync half-async design pattern
 
Composite Pattern
Composite PatternComposite Pattern
Composite Pattern
 
Bridge Pattern
Bridge PatternBridge Pattern
Bridge Pattern
 
Test Driven Development and JUnit
Test Driven Development and JUnitTest Driven Development and JUnit
Test Driven Development and JUnit
 

Recently uploaded

How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Jay Das
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 

Recently uploaded (20)

How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 

Observer pattern

  • 1. Observer Pattern in Java by Somenath Mukhopadhyay som-itsolutions
  • 2. As i was going through the different source code files of the Java Util package, i found the implementation of the Observer Pattern ( see the Gang of Four book for more information on this pattern) in the two places - namely Observer.java and Observable.java. i would like to throw some lights on these two classes. These two classes can be found in the Javaj2sesrcshareclassesjavautil folder of the JDK source code. But first of all, i need to give you a practical example of why we need observer pattern in the first place. Suppose, we have a document which can be viewed simultaneously by three different views – say one view represnts a line graph chart, another view represents it in a spreadsheet, yet another view represnts a pie chart. Now suppose the spreadsheet view makes some modification to the document. If the other two views don't update themselves with this changed state of the document, different views will be in inconsistent states. So we need some mechanism to notify the other two views whenever the spreadsheet view updates the document. This is done through Observer pattern in which whenever the document changes stete, it notifies all of its views. The views in turn updates themselves with the latest data. Fig 1: Class Diagram of Observer Pattern
  • 3. Fig 2: Sequence Diagram of Observer Pattern What these two diagrams essentially depict is that in the Observer Pattern, we have a Subject, which can attach one or more Observers through its Attach() function. Whenever it changes its state it Notifies all the attached Observers through its notify function. The observers in turn synchronize their states with that of the Subject through the GetSubjectState function. So now let us first start with the Observable.java class. As the name suggests it is the class which will implemented functionalities for being observed. Or in other words it is the class which helps in designing the Subject class of the Observer pattern discussion of the GoF book. We need to extend this class to get the Subject class. Let us try to dissect this class. The following functions are there in this class: 1. Data Members : It has a vector to hold all the observers that are interested in observing this observable class. It has another boolean data member called "changed" to indicate if anything has changed in the Subject class ( which will be derived from this Observable class). 2. Constructor : This class has a no argument constructor to construct an empty vector of Observers.
  • 4. 3. Member Functions :  addObserver : To add an observer to its list of Observers.  deleteObserver : To delete a particular observer from the list of the observers  notifyObservers : There are two overloaded versions of this function. One takes an Object parameter as an argument and the other does not take any argument. The task of this function is to notify all the attached observers when any data of the subject gets changed. To check whether the data is changed it evaluates the boolean "changed" data member. This function also calls the update function of each observer objects to ask them to get in sync with the subject's changed state. The overloaded version that takes an one argument parameter is used to let the observers know about which attribute is changed. And the other version of this function which does not take any argument does not let the observer know about which attribute is changed.  deleteObservers : This function removes all the observers attached to this subject.  setChanged : This function sets the boolean data member "changed".  clearChanged : This function resets the boolean data member "changed".  hasChanged : This function helps us to know whether the data of the subject has been changed or not.  countObservers : This function returns the number of observers attached to this subject. This is all about the Observable class which helps us to define to Subject class.
  • 5. The Observer.java defines an interface called Observer having just one abstract function called update (Observable o, Object arg). As the name suggests, the Observer class that will implement this interface will override the update function to set the attribute passed as an argument (arg) from the Subject class. This method is called whenever any attribute in the Subject class gets changed. Now let us try to see an example to understand how this Observer Pattern is used. Let us first extend the Observable class to create the Subject class. package com.somitsolutions.training.java.observerpattern; import java.util.Observable; public class Subject extends Observable { private String name; private float price; public Subject(String name, float price) { this.name = name; this.price = price; } public String getName() { return name; } public float getPrice() { return price; } public void setName(String name) { this.name = name; setChanged(); notifyObservers(name); } public void setPrice(float price) { this.price = price; setChanged(); notifyObservers(new Float(price)); } } As this is clear from the implementation of the Subject class, that whenever we call the setter function to change the attributes of the Subject's object, we call the notifyObservers and pass that attribute as a parameter. Now let us see how we create two different observers namely NameObserver and PriceObserver to observe these two attributes of the Subject class.
  • 6. // An observer of name changes. package com.somitsolutions.training.java.observerpattern; import java.util.Observable; import java.util.Observer; public class NameObserver implements Observer { private String name; public NameObserver() { name = null; System.out.println("NameObserver created: Name is " + name); } @Override public void update(Observable o, Object arg) { // TODO Auto-generated method stub if (arg instanceof String) { name = (String)arg; System.out.println("NameObserver: Name changed to " + name); } } }
  • 7. // An observer of price changes. package com.somitsolutions.training.java.observerpattern; import java.util.Observable; import java.util.Observer; public class PriceObserver implements Observer { private float price; public PriceObserver() { price = 0; System.out.println("PriceObserver created: Price is " + price); } @Override public void update(Observable o, Object arg) { // TODO Auto-generated method stub if (arg instanceof Float) { price = ((Float)arg).floatValue(); System.out.println("PriceObserver: Price changed to " + price); } } } As it has become clear from the above two implementations that the update function actually helps in synchronizing the state of the concrete observers with that of the Subject. Now the client of the Observer framework will look like the following :
  • 8. package com.somitsolutions.training.java.observerpattern; public class Main { public static void main(String args[]) { // Create the Subject and Observers. Subject s = new Subject("Kheer Kadam", 20.5f); NameObserver nameObs = new NameObserver(); PriceObserver priceObs = new PriceObserver(); // Add those Observers! s.addObserver(nameObs); s.addObserver(priceObs); //Initial Subject States System.out.println("Initial states of Subject"); System.out.println("Name : " + s.getName()); System.out.println("Price : " + Float.toString(s.getPrice())); // Make changes to the Subject. s.setName("Gulabjamun"); // It prints NameObserver: Name changed to Gulabjamun s.setPrice(15.0f); //It prints PriceObserver: Price changed to 15.0 s.setPrice(30.5f); //It prints PriceObserver: Price changed to 30.5 s.setName("Rasgulla"); // It prints NameObserver: Name changed to Rasgulla } } Hope the above discussion will help people understand of how the Java supports implementing the Observer pattern.