CodesJava

Easy learning with example program codes

java observer design pattern


Dictionary meaning of Observer: A person who watches or notices something.

Java observer design pattern comes under behavioural design patterns. According to GoF, observer design pattern states that define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Observer design pattern works with 3 classes which are Subject, Observer and Client. Subjects consists of list of observers and methods to attach and detach observers to a client object. It also contains a method to notify all the observers of any change.

MVC frameworks are the good example of observer design pattern. In MVC framework Model represents the Subject and Views refers to observers which can be registered to get notified of any change to the model.

Example

Subject.java

package com.codesjava;
 
import java.util.ArrayList;
import java.util.List;
 
public class Subject {
   private List<Observer> observers = new ArrayList<Observer>();
   private int state;
 
   public int getState() {
      return state;
   }
 
   public void setState(int state) {
      this.state = state;
      notifyAllObservers();
   }
 
   public void attach(Observer observer){
      observers.add(observer);		
   }
 
   public void notifyAllObservers(){
      for (Observer observer : observers) {
         observer.update();
      }
   } 		
}

Observer.java

package com.codesjava;
 
public abstract class Observer {
	protected Subject subject;
	public abstract void update();
}

StringObserver.java

package com.codesjava;
 
public class StringObserver extends Observer {
	public StringObserver(Subject subject){
	      this.subject = subject;
	      this.subject.attach(this);
	}
 
	@Override
	public void update() {
		System.out.println("String value: " + Integer.toString(subject.getState()));		
	}    	
}

OctalObserver.java

package com.codesjava;
 
public class OctalObserver extends Observer {
	public OctalObserver(Subject subject){
	      this.subject = subject;
	      this.subject.attach(this);
	}
 
	@Override
	public void update() {
		System.out.println("Octal value: " + Integer.toOctalString(subject.getState()));	
	}    	
}

ObserverPatternTest.java

package com.codesjava;
 
public class ObserverPatternTest {
  public static void main(String args[]){
      Subject subject = new Subject();
 
      new StringObserver(subject);
      new OctalObserver(subject);
 
      System.out.println("State change: 45");	
      subject.setState(45);
      System.out.println("State change: 150");	
      subject.setState(150);
  }
}

Output

State change: 45
String value: 45
Octal value: 55
State change: 150
String value: 150
Octal value: 226
Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki