Java Design Patterns Observer Patterns

Introduction

Observer Patterns define a one-to-many dependency between objects.

When one object changes state, all its dependents are notified and updated automatically.

In Observer Patterns, many observers are observing a particular subject.

Observers are notified when there is a change made inside that subject.

Observers can unregister from the subject.

Observer Patterns are referred to as the Publisher-Subscriber model.

Use cases

  • User interface can register to database change event. If the database changed, it will notify user interface.

Example

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

class Observer {
   public void update(int newValue) {
      System.out.println("new value:"+ newValue);
   }//from w  w  w .jav a 2s  .  c o  m
}

class Subject {
   List<Observer> observerList = new ArrayList<Observer>();
   private int myValue;

   public int getFlag() {
      return myValue;
   }

   public void setFlag(int v) {
      this.myValue = v;
      notifyObservers();
   }
   public void register(Observer o) {
      observerList.add(o);
   }
   public void unregister(Observer o) {
      observerList.remove(o);
   }
   public void notifyObservers() {
      for (int i = 0; i < observerList.size(); i++) {
         observerList.get(i).update(this.myValue);
      }
   }
}

public class Main {
   public static void main(String[] args) {
      Observer o1 = new Observer();
      Subject sub1 = new Subject();
      sub1.register(o1);
      sub1.setFlag(5);
      sub1.setFlag(25);
      sub1.unregister(o1);
      sub1.setFlag(50);
   }
}



PreviousNext

Related