Observer Design Pattern
Question :- What
is Observer Design Pattern?
Answer :- This
design pattern also falls under Behavioral
design pattern.
This(Observer) pattern defines one-to-many dependency means it
maintains a list of its dependents, called observers, and notifies
them automatically of any state changes, usually by calling one of
their methods.
The
participants which involves in this design pattern are :
Subject
:- Which contains a list of Observers in order to notify of any
change in it's state. It should provide methods using which observers
can register and unregister themselves.
Observer
:- Dependent items which is listening subject and registering or
unregistering based on the notification.
According
to GoF, observer pattern says that;
Define
a one-to-many dependency between objects so that when one object
changes state, all its dependents are notified and updated
automatically.
Question :- When
to use Observer design pattern?
Answer :-
If we have the requirement like in few scenario's watching for
changes and if changes are available notifying to all the dependents
elements then we should go with the pattern and this will give a
flexibility where Observer and Observable both are loosely coupled.
Advantage
of Observer Pattern:
- Observer and Observable are loosely coupled.
- Subject is only coupled with the Observer base class.
- Observers registers themselves with the subject.
- Subject published or broadcast events to all registered Observers.
- All the observers are notified with a single event.
- Client can configure types and number of observers.
Observer
design pattern in Real world :-
- We have seen option in stock market trading i.e. While trading through any demat a/c if we need some notification during the rate change then if rate change is available, it will notify to all the required clients.
- In few of the shopping site, if we are looking for some item and if that item size is not available then there is a option saying that Notify me which will help us to know whenever that item size will be available.
- Observer and Observable are a part of util package.
- HttpSessionBindingListener is an example where Observer design pattern in used in Java API.
Observer.java
package com.gaurav.designpattern.observer;
/**
* @author Gaurav
*
*/
public interface Observer {
public void updating(Observable observable, Object arg);
}
Observable.java
package com.gaurav.designpattern.observer;
/**
* @author Gaurav
*
*/
public interface Observable {
public void notifyingObservers();
public void registeringObserver(Observer observer);
public void removingObserver(Observer observer);
}
Stock.java
package com.gaurav.designpattern.observer;
/**
* @author Gaurav
*
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Stock implements Observable {
private List<Observer> observers;
private boolean isStockChanged;
private float hyundai;
private float maruti;
public Stock() {
observers = new ArrayList<Observer>();
}
public void registeringObserver(Observer observer) {
if (observer != null && observer instanceof Observer) {
this.observers.add(observer);
}
}
public void removingObserver(Observer observer) {
if (observer != null && observer instanceof Observer) {
this.observers.remove(observer);
}
}
public void notifyingObservers() {
Iterator<Observer> observerIterator = this.observers.listIterator();
while (observerIterator.hasNext()) {
Observer observer = observerIterator.next();
observer.updating(this, null);
}
}
public float getHyundai() {
return hyundai;
}
public void setHyundai(float hyundai) {
if (this.hyundai != hyundai) {
this.isStockChanged = true;
this.hyundai = hyundai;
}
this.setStockChanged();
}
public float getMaruti() {
return maruti;
}
public void setMaruti(float maruti) {
if (this.maruti != maruti) {
this.isStockChanged = true;
this.maruti = maruti;
}
this.setStockChanged();
}
public void setStockChanged() {
this.notifyingObservers();
}
}
Publish.java
package com.gaurav.designpattern.observer;
/**
* @author Gaurav
*
*/
public interface Publish {
public void publishing(String message);
}
MessagePropagator.java
package com.gaurav.designpattern.observer;
/**
* @author Gaurav
*
*/
import java.util.Calendar;
public class MessagePropagator implements Observer,Publish{
public void updating(Observable observable, Object arg) {
Stock stock = (Stock)observable;
String message = "Hyundai Stock change details are :"+stock.getHyundai()+" and Maruti :"
+stock.getMaruti()+" at "+Calendar.getInstance().getTime();
this.publishing(message);
}
public void publishing(String msg) {
System.out.println(msg);
}
}
ObserverDesignPatternDemo.java
package com.gaurav.designpattern.observer;
/**
* @author Gaurav
*
*/
public class ObserverDesignPatternDemo {
public static void main(String[] args) {
Stock stock = new Stock();
MessagePropagator messagePropagator = new MessagePropagator();
stock.registeringObserver(messagePropagator);
stock.setHyundai(11);
stock.setMaruti(26);
}
}
Result:-
Hyundai Stock change details are :11.0 and Maruti :0.0 at Tue May 12 14:20:27 IST 2015
Hyundai Stock change details are :11.0 and Maruti :26.0 at Tue May 12 14:20:27 IST 2015
Hi,
ReplyDeleteVery useful information is provided with examples. Thanks for posting. Keep posting.
http://kosmiktechnologies.com/java-training-institutes-in-kukatpally/