Friday, May 27, 2016

Design Pattern - Observer Pattern tutorial example java

What is Observer Pattern?

Yes, Observer Pattern is Behavioral Design Pattern.In the Observer pattern ,an object called subject maintains a collect of objects called Observers. when the subject changes it notifies the observers.

For Example:
The observer pattern defines a link between objects so that when one objects state changes all dependent objects are updated automatically.a very famous example of Producer-Consumer problem in core java.

So, Observer pattern is designed to help cope with one to many relationships between objects allowing changes in an object to update many associated objects.


When to use Observer Pattern:

  • when a change to one object requires changing others and we do not 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.
  • when an abstraction has two aspects  one depends on the other.
Implementation:


public interface TempratureSubject
{
  public void addObserver(TempratureObserver TempratureObserver);
  public void removeObserver(TempratureObserver TempratureObserver);
  public void notify();
}

public interface TempratureObserver 
{
  public void update(int temparature);
}

public class TemparatureStation implements TempratureSubject
{
  Set<TempratureObserver> temparatureObservers;
  int temparature;
  
  public TemparatureStation(int temp)
  {
    this.temparature=temp;
  }
  
  public void addObserver(TempratureObserver tempObserver)
  {
    temparatureObservers.add(tempObserver);
  }
  
  public void removeObserver(TempratureObserver tempObserver)
  {
    temparatureObservers.add(tempObserver);
  }
  
  public void notify()
  {
    Iterator<TempratureObserver> it=tempObserver.iterator();
while(it.hasNext)
{
  TempratureObserver tempObserver= it.next();
  tempObserver.update(temparature);
}
  }
  
  public void setTemparature(int newTemparature)
  {
     System.out.println("Setting temparature to " + newTemparature); 
     temparature=newTemparature;
notify();
           
  }  
}



how client will use this pattern?Let say,

public class TempratureCustmer implements TempratureObserver
{
  public void update(int temparature)
  {
    System.out.println("Customer 1 found the temparature as"+ temparature);
  }
}

public class observerTest
{
  public static void main(String args[])
  {
    TemparatureStation tempStation=new  TemparatureStation();
TempratureCustmer tcustomer=new TempratureCustmer();
tempStation.addObserver(tcustomer);
tempStation.removeObserver(tcustomer);
tempStation.setTemparature(35);
  }
}

Very Important Points to remember before using Observer pattern

  • Also known as Depedents ,Publish-Subscibe patterns.
  • Define one to many dependency between objects.
  • Abstract coupling between subject and obsever.
  • Unexpected updates because observer have no knowledge of each others presence. 

No comments: