Tuesday, March 7, 2023

Java Observer Pattern

Java Observer Pattern

This pattern defines a one-to-many dependency between objects, so that when one object changes state, all its dependents are notified and updated automatically.

The Observer pattern is a design pattern used in object-oriented programming. In Java, it is implemented using the java.util.Observer interface and java.util.Observable class.

The Observer pattern defines a one-to-many relationship between objects. In this relationship, one object (called the subject or the observable) maintains a list of its dependents (called observers) and notifies them automatically whenever its state changes.

To implement the Observer pattern in Java, you need to follow these steps:

  1. Create the Subject class: This class maintains the state of the object and keeps track of its observers. It should have methods to register and unregister observers, and to notify them when the state changes. The Subject class should also extend the java.util.Observable class.

  2. Create the Observer interface: This interface should define the update() method, which is called by the Subject whenever its state changes. The Observer interface should also implement the java.util.Observer interface.

  3. Create the ConcreteSubject class: This class implements the Subject interface and provides concrete implementations of the methods defined in it.

  4. Create the ConcreteObserver class: This class implements the Observer interface and provides concrete implementations of the update() method.

Here is an example implementation of the Observer pattern in Java:


import java.util.Observable;
import java.util.Observer;
public class Subject extends Observable {
   private int state;
   public int getState() {
      return state;
   }
   public void setState(int state) {
      this.state = state;
      setChanged();
      notifyObservers();
   }
}
public class Observer implements java.util.Observer {
   @Override
   public void update(Observable o, Object arg) {
      System.out.println("State changed to " + ((Subject) o).getState());
   }
}
public class Main {
   public static void main(String[] args) {
      Subject subject = new Subject();
      Observer observer = new Observer();
      subject.addObserver(observer);
      subject.setState(1);
      subject.setState(2);
   }
}

In this example, the Subject class extends the java.util.Observable class, and the Observer class implements the java.util.Observer interface. The Main class creates a Subject object and an Observer object, and registers the Observer object with the Subject object using the addObserver() method. Whenever the state of the Subject object changes, the notifyObservers() method is called to notify all its registered observers. 

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home