Java Design Patterns Observer Patterns with interface

Introduction

The following code adds interfaces to the Subject and Observers.

Example

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

interface IObserver {
   void update(int i);
}

class Observer1 implements IObserver {
   @Override/*from  w  ww .ja v  a  2s .c  om*/
   public void update(int i) {
      System.out.println("Observer1: myValue is: " + i);
   }
}

class Observer2 implements IObserver {
   @Override
   public void update(int i) {
      System.out.println("Observer2: myValue is:" + i);
   }
}

interface ISubject {
   void register(IObserver o);

   void unregister(IObserver o);

   void notifyObservers(int i);
}

class Subject implements ISubject {
   private int myValue;
   private List<IObserver> observersList = new ArrayList<IObserver>();

   public int getMyValue() {
      return myValue;
   }

   public void setMyValue(int myValue) {
      this.myValue = myValue;
      notifyObservers(myValue);
   }
   @Override
   public void register(IObserver o) {
      observersList.add(o);
   }
   @Override
   public void unregister(IObserver o) {
      observersList.remove(o);
   }

   @Override
   public void notifyObservers(int updatedValue) {
      for (int i = 0; i < observersList.size(); i++) {
         observersList.get(i).update(updatedValue);
      }
   }
}

public class Main {
   public static void main(String[] args) {
      Subject sub = new Subject();
      Observer1 ob1 = new Observer1();
      Observer2 ob2 = new Observer2();

      sub.register(ob1);
      sub.register(ob2);

      sub.setMyValue(5);
      sub.setMyValue(25);
      sub.unregister(ob1);
      sub.setMyValue(100);
   }
}



PreviousNext

Related