JaiswalTraining

Get the online training



Corejava Servlet Jsp  Php  Hibernate  Ajax Web Service   Ejb2.1 Ejb3.0 Struts Struts2  JPA Spring Ibatis   JSF    JSF2.0  CoreJavaDesignPattern    Jquery  Flex J2EE-Design-Patterns  Jboss7  Maven  Contact Me                                                                                                                                                                        
            IGNOU SMU PTU Project                                           Training                                                                                                                              
              

Contact Us  0091- 9210721663         jaiswaltraining@gmail.com




Corejava
Servlet
Jsp
Php
Hibernate
Ajax
Web Service
Ejb2.1
Ejb3.0
Struts  
Struts2
JPA
Spring
Ibatis
JSF
JSF2.0
CoreJavaDesignPattern
Jquery
Flex
J2EE-Design-Patterns
Jboss7
Maven







Observer Pattern
  • The observer pattern (a subset of the asynchronous publish/subscribe pattern) is a software
    design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.
  •  It is mainly used to implement distributed event handling systems
Purpose
  • Define a one-to-many dependency between objects so that when one object changes
    state, all its dependents are notified and updated automatically.

Applications
  • When an abstraction has two aspects, one dependent on the other.
    Encapsulating these aspects in separate objects lets you vary and reuse them
    independently.
  • When a change to one object requires changing others, and you don't know how
    many objects need to be changed.
  • When an object should be able to notify other objects without making
    assumptions about who these objects are. In other words, you don't want these
    objects tightly coupled.
Interaction


  • ConcreteSubject notifies its observers whenever a change occurs that could make
    its observers' state inconsistent with its own.
  • After being informed of a change in the concrete subject, a ConcreteObserver
    object may query the subject for information.
  •  ConcreteObserver uses this information to reconcile its state with that of the
    subject.
Non-software examples of Observer design patterns

The Observer defines a one-to-many relationship so that when one object
changes state, the others are notified and updated automatically

Some auctions demonstrate this pattern. Each bidder possesses a numbered paddle that is used
to indicate a bid. The auctioneer starts the bidding, and "observes" when a
paddle is raised to accept the bid. The acceptance of the bid changes the bid
price which is broadcast to all of the bidders in the form of a new bid.

Example:-1

Interest.java

package com.controllers;

public enum Interest {
FDA, HOUSING_LOAN, BUSINESS_LOAN;
}

Observer.java
package com.controllers;

public interface Observer {
  void update(String msg);
  void addInterest(Interest interest);
  void removeInterest(Interest interest);
}

Subject.java
package com.controllers;

public interface Subject {
void register(Observer obs);
void addInterest(Observer obs, Interest interest);
void removeInterest(Observer obs, Interest interest);
void update(double roi, Interest interest);
void unregister(Observer obs);
}


ChangeProvider.java
package com.model;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.controllers.Interest;
import com.controllers.Observer;
import com.controllers.Subject;

public class ChangeProvider implements Subject{

  private List<Client> clients; 
  private Map<Interest, Double> interests;
  @Override
  public void register(Observer obs) {
    // TODO Auto-generated method stub
  
    clients.add(new Client(obs));
  }
  
  public ChangeProvider() {
    super();
    // TODO Auto-generated constructor stub
    clients=new LinkedList<Client>();
    interests=new HashMap<Interest, Double>();
  }

  @Override
  public void removeInterest(Observer obs, Interest interest) {
    // TODO Auto-generated method stub
    for(Client c:clients)
      if(c.equals(obs))
        c.removeInterest(interest);
  }

  @Override
  public void update(double roi, Interest interest) {
    // TODO Auto-generated method stub
    interests.put(interest, roi);
    notifyAll(interest);
  }
  void notifyAll(Interest interest){
    for(Client  c: clients)
    {
      if(c.hasInterest(interest))
        c.getObs().update(" "+interest+" Updated");
    }
  }
  @Override
  public void unregister(Observer obs) {
    // TODO Auto-generated method stub
    clients.remove(obs);
  }

  @Override
  public void addInterest(Observer obs, Interest interest) {
    // TODO Auto-generated method stub
    for(Client c:clients){
      if(c.getObs().equals(obs))
        c.addInterest(interest);
    }
  }

}

Client.java
package com.model;

import java.util.ArrayList;
import java.util.List;

import com.controllers.Interest;
import com.controllers.Observer;

public class Client {
  private Observer obs;
  private List<Interest> interests;
  void addInterest(Interest its){
    if(interests==null)
      interests=new ArrayList<Interest>();
    interests.add(its);
  }
  public Client(Observer obs) {
    super();
    this.obs = obs;
  }
  public void removeInterest(Interest interest){
    interests.remove(interest);
  }
  public boolean hasInterest(Interest its){
    return interests.contains(its);
  }
  public Observer getObs() {
    return obs;
  }
  public void setObs(Observer obs) {
    this.obs = obs;
  }
  
}

View1.java
package com.views;

import com.controllers.Interest;
import com.controllers.Observer;
import com.controllers.Subject;

public class View1 implements Observer{
  Subject subject;
  
  public View1(Subject subject) {
    super();
    this.subject = subject;
    subject.register(this);
  }

  public View1() {
    super();
    // TODO Auto-generated constructor stub
  }
  
  @Override
  public void update(String msg) {
    // TODO Auto-generated method stub
    System.out.println(msg);
  }

  @Override
  public void addInterest(Interest interest) {
    // TODO Auto-generated method stub
    subject.addInterest(this, interest);
  }

  @Override
  public void removeInterest(Interest interest) {
    // TODO Auto-generated method stub
    subject.removeInterest(this, interest);
  }

}


View2.java
package com.views;

import com.controllers.Interest;
import com.controllers.Observer;
import com.controllers.Subject;

public class View2 implements Observer {
Subject subject;
  
  public View2(Subject subject) {
    super();
    this.subject = subject;
    subject.register(this);
  }

  public View2() {
    super();
    // TODO Auto-generated constructor stub
  }
  
  @Override
  public void update(String msg) {
    // TODO Auto-generated method stub
    javax.swing.JOptionPane.showMessageDialog(null, msg);
  }

  @Override
  public void addInterest(Interest interest) {
    // TODO Auto-generated method stub
    subject.addInterest(this, interest);
  }
  @Override
  public void removeInterest(Interest interest) {
    // TODO Auto-generated method stub
    subject.removeInterest(this, interest);
  }

}

Test.java
package com.test;

import com.controllers.Interest;
import com.model.ChangeProvider;
import com.views.View1;
import com.views.View2;

public class Test {

  /**
   @param args
   */
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    ChangeProvider provider = new ChangeProvider();
    
    View1 v1=new View1(provider);
    View2 v2=new View2(provider);
    
    v1.addInterest(Interest.FDA);
    v1.addInterest(Interest.BUSINESS_LOAN);
    v1.addInterest(Interest.HOUSING_LOAN);
    
    v2.addInterest(Interest.HOUSING_LOAN);
    v2.addInterest(Interest.FDA);
    
    
    provider.update(10, Interest.BUSINESS_LOAN);
    provider.update(10, Interest.HOUSING_LOAN);
    provider.update(23,Interest.FDA);
    
  //  v1.removeInterest(Interest.FDA);
    
//    provider.update(23,Interest.FDA);
    
  }

}

Output:-



Download Zip Code

Example:-2

Observer.java
abstract class Observer
{
  public abstract void Update();

}

Subject.java
import java.util.*;

abstract class Subject

{
  private List<Observer> _observers = new ArrayList<Observer>();

  public void Attach(Observer observer)

  {

    _observers.add(observer);

  }

  public void Detach(Observer observer)

  {

    _observers.remove(observer);

  }

  public void Notify()

  {

    for (Observer o : _observers)

    {

      o.Update();

    }

  }

}

ConcreteObserver.java
class ConcreteObserver extends Observer

{

  private String _name;

  private String _observerState;

  private ConcreteSubject _subject;

  // Constructor

  public ConcreteObserver(

  ConcreteSubject subject, String name)

  {

    this._subject = subject;

    this._name = name;

  }

  public void Update()

  {

    _observerState = _subject.getSubjectState();

    System.out.println("Observer " + _name + "'s new state is "
        + _observerState);

  }

  // Gets or sets subject

  public ConcreteSubject getSubject()

  {

    return _subject;
  }

  public void setSubject(ConcreteSubject value) {
    _subject = value;

  }

}

ConcreteSubject.java
 class ConcreteSubject extends Subject

  {

    private String _subjectState;

 

    // Gets or sets subject state

    public String getSubjectState()

    {

       return _subjectState; 
    
    }
    public void setSubjectState(String value)

    {

       _subjectState = value;
    
    }
 


    

  }

TestApp.java

public class TestApp

{

  public static void main(String[] arg)

  {

    // Configure Observer pattern

    ConcreteSubject s = new ConcreteSubject();

    s.Attach(new ConcreteObserver(s, "X"));
    s.setSubjectState("ABC");
    s.Notify();
    s.Attach(new ConcreteObserver(s, "Y"));
    s.setSubjectState("aaa");
    s.Notify();
    s.Attach(new ConcreteObserver(s, "Z"));
    s.setSubjectState("AAA");

    // Change subject and notify observers

    // s.setSubjectState("ABC");

    s.Notify();

    // Wait for user

    System.out.println("BYEEEEEEEEEEEEEEEE");

  }

}

Output:-

Downlaod Zip code

Example:-3

DvdRelease.java
public class DvdRelease {  
   private String serialNumber;
   private String dvdName; 
   private int dvdReleaseYear;
   private int dvdReleaseMonth;
   private int dvdReleaseDay;

   
   public DvdRelease(String serialNumber, 
                     String dvdName, 
                     int dvdReleaseYear, 
                     int dvdReleaseMonth, 
                     int dvdReleaseDay) {
       setSerialNumber(serialNumber);
       setDvdName(dvdName);
       setDvdReleaseYear(dvdReleaseYear);
       setDvdReleaseMonth(dvdReleaseMonth);
       setDvdReleaseDay(dvdReleaseDay);       
   }
   
   public void updateDvdRelease(String serialNumber, 
                                String dvdName, 
                                int dvdReleaseYear, 
                                int dvdReleaseMonth, 
                                int dvdReleaseDay) {
       setSerialNumber(serialNumber);
       setDvdName(dvdName);
       setDvdReleaseYear(dvdReleaseYear);
       setDvdReleaseMonth(dvdReleaseMonth);
       setDvdReleaseDay(dvdReleaseDay);        
   }   
   
   public void updateDvdReleaseDate(int dvdReleaseYear, 
                                    int dvdReleaseMonth, 
                                    int dvdReleaseDay) {
       setDvdReleaseYear(dvdReleaseYear);
       setDvdReleaseMonth(dvdReleaseMonth);
       setDvdReleaseDay(dvdReleaseDay);        
   }   
   
   public void setSerialNumber(String serialNumberIn) {
       this.serialNumber = serialNumberIn;
   }
   public String getSerialNumber() {
       return this.serialNumber;
   }
   
   public void setDvdName(String dvdNameIn) {
       this.dvdName = dvdNameIn;
   }
   public String getDvdName() {
       return this.dvdName;
   }
   
   public void setDvdReleaseYear(int dvdReleaseYearIn) {
       this.dvdReleaseYear = dvdReleaseYearIn;
   }
   public int getDvdReleaseYear() {
       return this.dvdReleaseYear;
   }
   
   public void setDvdReleaseMonth(int dvdReleaseMonthIn) {
       this.dvdReleaseMonth = dvdReleaseMonthIn;
   }
   public int getDvdReleaseMonth() {
       return this.dvdReleaseMonth;
   }
   
   public void setDvdReleaseDay(int dvdReleaseDayIn) {
       this.dvdReleaseDay = dvdReleaseDayIn;
   }
   public int getDvdReleaseDay() {
       return this.dvdReleaseDay;
   }
}

DvdReleaseByCategory.java
import java.util.ArrayList;
import java.util.ListIterator;

public class DvdReleaseByCategory {  
   String categoryName; 
   ArrayList subscriberList = new ArrayList();
   ArrayList dvdReleaseList = new ArrayList();   
   
   public DvdReleaseByCategory(String categoryNameIn) {
       categoryName = categoryNameIn;
   }
   
   public String getCategoryName() {
       return this.categoryName;
   }
   
   public boolean addSubscriber(DvdSubscriber dvdSubscriber) {
       return subscriberList.add(dvdSubscriber);
   }
   
   public boolean removeSubscriber(DvdSubscriber dvdSubscriber) {
       ListIterator listIterator = subscriberList.listIterator();
       while (listIterator.hasNext()) {
           if (dvdSubscriber == (DvdSubscriber)(listIterator.next())) {
               listIterator.remove();
               return true;
           }
       }
       return false;
   }
   
   public void newDvdRelease(DvdRelease dvdRelease) {
       dvdReleaseList.add(dvdRelease);
       notifySubscribersOfNewDvd(dvdRelease);
   }
   
   public void updateDvd(DvdRelease dvdRelease) {
       boolean dvdUpdated = false;
       DvdRelease tempDvdRelease;
       ListIterator listIterator = dvdReleaseList.listIterator();
       while (listIterator.hasNext()) {
           tempDvdRelease = (DvdRelease)listIterator.next();
           if (dvdRelease.getSerialNumber().
                 equals(tempDvdRelease.getSerialNumber())) {
               listIterator.remove();
               listIterator.add(dvdRelease);
               dvdUpdated = true;
               break;
           }
       }
       if (dvdUpdated == true) {
           notifySubscribersOfUpdate(dvdRelease);
       else 
           this.newDvdRelease(dvdRelease);
       }
   }
   
   private void notifySubscribersOfNewDvd(DvdRelease dvdRelease) {
       ListIterator listIterator = subscriberList.listIterator();
       while (listIterator.hasNext()) {
           ((DvdSubscriber)(listIterator.next())).
               newDvdRelease(dvdRelease, this.getCategoryName());
       }
   }

   private void notifySubscribersOfUpdate(DvdRelease dvdRelease) {
       ListIterator listIterator = subscriberList.listIterator();
       while (listIterator.hasNext()) {
           ((DvdSubscriber)(listIterator.next())).
               updateDvdRelease(dvdRelease, this.getCategoryName() );
       }       
   }
}

DvdSubscriber.java
public class DvdSubscriber {  
   private String subscriberName; 
   
   public DvdSubscriber(String subscriberNameIn) {
       this.subscriberName = subscriberNameIn;
   }
   
   public String getSubscriberName() {
       return this.subscriberName;
   }
   
   public void newDvdRelease(DvdRelease newDvdRelease, 
                             String subscriptionListName) {
       System.out.println("");
       System.out.println("Hello " this.getSubscriberName() 
                          ", subscriber to the " 
                             subscriptionListName + 
                          " DVD release list.");
       System.out.println("The new Dvd " 
                            newDvdRelease.getDvdName() 
                          " will be released on " 
                            newDvdRelease.getDvdReleaseMonth() "/" 
                            newDvdRelease.getDvdReleaseDay() "/" 
                            newDvdRelease.getDvdReleaseYear() ".");
   }
   
   public void updateDvdRelease(DvdRelease newDvdRelease, 
                                String subscriptionListName) {
       System.out.println("");
       System.out.println("Hello " this.getSubscriberName() 
                          ", subscriber to the " 
                            subscriptionListName +
                          " DVD release list.");
       System.out.println(
         "The following DVDs release has been revised: " 
         newDvdRelease.getDvdName() " will be released on " 
         newDvdRelease.getDvdReleaseMonth() "/" 
         newDvdRelease.getDvdReleaseDay() "/" 
         newDvdRelease.getDvdReleaseYear() ".");
   }   
}

TestDvdObserver.java
class TestDvdObserver {
    
   public static void main(String[] args) {
       DvdReleaseByCategory btvs = 
           new DvdReleaseByCategory("Buffy the Vampire Slayer");
       DvdReleaseByCategory simpsons = 
           new DvdReleaseByCategory("The Simpsons");  
       DvdReleaseByCategory sopranos = 
           new DvdReleaseByCategory("The Sopranos");
       DvdReleaseByCategory xfiles = 
           new DvdReleaseByCategory("The X-Files");
       
       DvdSubscriber jsopra = new DvdSubscriber("Junior Soprano");
       DvdSubscriber msimps = new DvdSubscriber("Maggie Simpson");
       DvdSubscriber rgiles = new DvdSubscriber("Rupert Giles");
       DvdSubscriber smulde = new DvdSubscriber("Samantha Mulder");
       DvdSubscriber wrosen = new DvdSubscriber("Willow Rosenberg");

       btvs.addSubscriber(rgiles);
       btvs.addSubscriber(wrosen);  
       simpsons.addSubscriber(msimps);
       sopranos.addSubscriber(jsopra);
       xfiles.addSubscriber(smulde);
       xfiles.addSubscriber(wrosen);
       
       DvdRelease btvsS2 = 
         new DvdRelease("DVDFOXBTVSS20"
                        "Buffy The Vampire Slayer Season 2",
                         20100611);
       DvdRelease simpS2 = 
         new DvdRelease("DVDFOXSIMPSO2"
                        "The Simpsons Season 2",
                         201007,  9);
       DvdRelease soprS2 = 
         new DvdRelease("DVDHBOSOPRAS2"
                        "The Sopranos Season 2",
                         201111,  6);
       DvdRelease xfilS5 = 
         new DvdRelease("DVDFOXXFILES5"
                        "The X-Files Season 5",
                         201004,  1);
       
       btvs.newDvdRelease(btvsS2);
       simpsons.newDvdRelease(simpS2);
       sopranos.newDvdRelease(soprS2);
       xfiles.newDvdRelease(xfilS5);
       
       xfiles.removeSubscriber(wrosen);
       
       xfilS5.updateDvdReleaseDate(2010514);
       xfiles.updateDvd(xfilS5);
   }
}      

Output:-

Download Zip code


Example:-3

Observer.java

package observer.weather;

public interface Observer {
  public void update(float temp, float humidity, float pressure);
}

CurrentConditionsDisplay.java
package observer.weather;
  
public class CurrentConditionsDisplay
implements Observer, DisplayElement {
  private float temperature;
  private float humidity;
  private Subject weatherData;
  
  public CurrentConditionsDisplay(Subject weatherData) {
    this.weatherData = weatherData;
    weatherData.registerObserver(this);
  }
  
  public void update(float temperature,
float humidity, float pressure) {
    this.temperature = temperature;
    this.humidity = humidity;
    display();
  }
   
  public void display() {
    System.out.println("Current
conditions: " 
+ temperature 
      "F degrees and " + humidity + "% humidity");
  }
}

DisplayElement.java
package observer.weather;

public interface DisplayElement {
  public void display();
}

ForecastDisplay.java
package observer.weather;

import java.util.*;

public class ForecastDisplay implements
Observer, DisplayElement 
{
  private float currentPressure = 29.92f;  
  private float lastPressure;
  private WeatherData weatherData;

  public ForecastDisplay(WeatherData weatherData) {
    this.weatherData = weatherData;
    weatherData.registerObserver(this);
  }

  public void update(float temp, float humidity,
 
float pressure) {
                lastPressure = currentPressure;
    currentPressure = pressure;

    display();
  }

  public void display() {
    System.out.print("Forecast: ");
    if (currentPressure > lastPressure) {
      System.out.println("Improving weather
 on the way!"
);
    else if (currentPressure == lastPressure) {
      System.out.println("More of the same");
    else if (currentPressure < lastPressure) {
      System.out.println("Watch out for cooler,
rainy weather"
);
    }
  }
}

HeatIndexDisplay
package observer.weather;

public class HeatIndexDisplay
 
implements Observer, DisplayElement {
  float heatIndex = 0.0f;
  private WeatherData weatherData;

  public HeatIndexDisplay(WeatherData weatherData) {
    this.weatherData = weatherData;
    weatherData.registerObserver(this);
  }

  public void update(float t, float rh, float pressure) {
    heatIndex = computeHeatIndex(t, rh);
    display();
  }
  
  private float computeHeatIndex(float t, float rh) {
    float index = (float)((16.923 +
(
0.185212 * t(5.37941 * rh(0.100254 * t * rh
      (0.00941695 (t * t)) +
(0.00728898 (rh * rh)) 
      (0.000345372 (t * t * rh))
 
(0.000814971 (t * rh * rh)) +
      (0.0000102102 (t * t * rh * rh))
 
(0.000038646 (t * t * t)) (0.0000291583 
      (rh * rh * rh)) (0.00000142721 (t * t * t * rh)) 
      (0.000000197483 (t * rh * rh * rh))
 
(0.0000000218429 (t * t * t * rh * rh)) +
      0.000000000843296 (t * t * rh * rh * rh)) -
      (0.0000000000481975 (t * t * t * rh * rh * rh)));
    return index;
  }

  public void display() {
    System.out.println("Heat index is "
+ heatIndex);
  }
}

StatisticsDisplay.java
package observer.weather;

import java.util.*;

public class StatisticsDisplay implements
 
Observer, DisplayElement {
  private float maxTemp = 0.0f;
  private float minTemp = 200;
  private float tempSum= 0.0f;
  private int numReadings;
  private WeatherData weatherData;

  public StatisticsDisplay(WeatherData weatherData) {
    this.weatherData = weatherData;
    weatherData.registerObserver(this);
  }

  public void update(float temp, float
 
humidity, float pressure) {
    tempSum += temp;
    numReadings++;

    if (temp > maxTemp) {
      maxTemp = temp;
    }
 
    if (temp < minTemp) {
      minTemp = temp;
    }

    display();
  }

  public void display() {
    System.out.println("Avg/Max/Min temperature =
(tempSum / numReadings)
      "/" + maxTemp + "/" + minTemp);
  }
}

Subject.java
package observer.weather;

public interface Subject {
  public void registerObserver(Observer o);
  public void removeObserver(Observer o);
  public void notifyObservers();
}

WeatherData.java
package observer.weather;

import java.util.*;

public class WeatherData implements Subject {
  private ArrayList observers;
  private float temperature;
  private float humidity;
  private float pressure;
  
  public WeatherData() {
    observers = new ArrayList();
  }
  
  public void registerObserver(Observer o) {
    observers.add(o);
  }
  
  public void removeObserver(Observer o) {
    int i = observers.indexOf(o);
    if (i >= 0) {
      observers.remove(i);
    }
  }
  
  public void notifyObservers() {
    for (int i = 0; i < observers.size(); i++) {
      Observer observer = (Observer)observers.get(i);
      observer.update(temperature, humidity, pressure);
    }
  }
  
  public void measurementsChanged() {
    notifyObservers();
  }
  
  public void setMeasurements(float temperature, float
humidity, float pressure) {
    this.temperature = temperature;
    this.humidity = humidity;
    this.pressure = pressure;
    measurementsChanged();
  }
  
  public float getTemperature() {
    return temperature;
  }
  
  public float getHumidity() {
    return humidity;
  }
  
  public float getPressure() {
    return pressure;
  }
}

WeatherStation.java
package observer.weather;

import java.util.*;

public class WeatherStation {

  public static void main(String[] args) {
    WeatherData weatherData = new WeatherData();
  
    CurrentConditionsDisplay currentDisplay = 
      new CurrentConditionsDisplay(weatherData);
    StatisticsDisplay statisticsDisplay =
 
new StatisticsDisplay(weatherData);
    ForecastDisplay forecastDisplay =
 
new ForecastDisplay(weatherData);

    weatherData.setMeasurements(806530.4f);
    weatherData.setMeasurements(827029.2f);
    weatherData.setMeasurements(789029.2f);
  }
}

Output:-



WeatherStationHeatIndex.java
package observer.weather;

import java.util.*;

public class WeatherStationHeatIndex {

  public static void main(String[] args) {
    WeatherData weatherData = new WeatherData();
    CurrentConditionsDisplay currentDisplay =
new CurrentConditionsDisplay(weatherData);
    StatisticsDisplay statisticsDisplay = new
StatisticsDisplay(weatherData);
    ForecastDisplay forecastDisplay = new
ForecastDisplay(weatherData);
    HeatIndexDisplay heatIndexDisplay = new
HeatIndexDisplay
(weatherData);

    weatherData.setMeasurements(806530.4f);
    weatherData.setMeasurements(827029.2f);
    weatherData.setMeasurements(789029.2f);
  }
}

Output:

Download Zip code