Java Design Patterns Observer Patterns with multiple observers and multiple subjects

Introduction

The following code implements an observer pattern with multiple observers and multiple subjects.

Example

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

interface IObserver {
   void update(String s, int i);
}

class Observer1 implements IObserver {
   @Override// w  ww .  j av  a 2 s .co  m
   public void update(String s, int i) {
      System.out.println("Observer1: myValue in " + s + " is now: " + i);
   }
}

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

class Observer3 implements IObserver {
   @Override
   public void update(String s, int i) {
      System.out.println("Observer3: myValue in " + s + " is now :" + i);
   }
}

interface ISubject {
   void register(IObserver o);

   void unregister(IObserver o);

   void notifyObservers(int i);
}

class Subject1 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(this.getClass().getSimpleName(), updatedValue);
      }
   }
}

class Subject2 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(this.getClass().getSimpleName(), updatedValue);
      }
   }
}

public class Main {
   public static void main(String[] args) {
      Subject1 sub1 = new Subject1();
      Subject2 sub2 = new Subject2();

      Observer1 ob1 = new Observer1();
      Observer2 ob2 = new Observer2();
      Observer3 ob3 = new Observer3();

      sub1.register(ob1);
      sub1.register(ob2);

      sub2.register(ob2);
      sub2.register(ob3);

      sub1.setMyValue(50);

      sub2.setMyValue(250);

      sub1.unregister(ob2);

      sub1.setMyValue(550);

      sub2.setMyValue(750);
   }
}



PreviousNext

Related