How to Implement Observer Pattern in Java


Here this example focuses on how to implement Observer Pattern in Java.

Source Code

1)

package com.beginner.examples;

import java.util.List;
import java.util.ArrayList;
 
public class Observer1 {
   
   private List observers = new ArrayList();
   private int state;
 
   public int getState() {
      return state;
   }
 
   public void setState(int state) {
      this.state = state;
      notifyAllObservers();
   }
   
   // notify all observers
   public void notifyAllObservers(){
      for (Observer2 observer : observers) {
         observer.update();
      }
   }
   
   public void attach(Observer2 observer){
      observers.add(observer);      
   }
}

2)

package com.beginner.examples;

public abstract class Observer2 {
	   protected Observer1 s;
	   public abstract void update();
	}

3)

package com.beginner.examples;

public class Observer3 extends Observer2{
	 
	   public Observer3(Observer1 s){
	      this.s = s;
	      this.s.attach(this);
	   }
	 
	   @Override
	   public void update() {
	      System.out.println("Observer 3"); 
	   }
	}

4)

package com.beginner.examples;

public class Observer4 extends Observer2{
	 
	   public Observer4(Observer1 s){
	      this.s = s;
	      this.s.attach(this);
	   }
	 
	   @Override
	   public void update() {
	     System.out.println( "Observer 4"); 
	   }
	}

5)

package com.beginner.examples;

public class Observer5 extends Observer2{
	 
	   public Observer5(Observer1 s){
	      this.s = s;
	      this.s.attach(this);
	   }
	 
	   @Override
	   public void update() {
	      System.out.println( "Observer 5"); 
	   }
	}

6)

package com.beginner.examples;

public class ObserverExample {
	   public static void main(String[] args) {
		  Observer1 o = new Observer1();
		  new Observer3(o);
	      new Observer4(o);
	      new Observer5(o);
	 
	      System.out.println("First state change: ");
	      // set state
	      o.setState(0);
	      System.out.println("Second state change: ");  
	      o.setState(1);
	   }
	}

Output:

First state change: 
Observer 3
Observer 4
Observer 5
Second state change: 
Observer 3
Observer 4
Observer 5
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments