Sunday 16 October 2011

Java implementation of Call Back Method- Observer Pattern

Call back method mechanism is based on the Observer pattern.


Prerequisite in understanding this implementation:
The java's concept of Polymorphsim plays big in the implementation of Observer pattern, so you have to be comfortable with this concept.

Building blocks of the call back method:

1.       Observer
2.       Subject
3.       Interface


Observer
What it means is that the object will wait and observe for an event to occur, and when the event occurs it will do something special, i.e. a special method that it defines, get run.  This object is called the Observer.

Subject
There is another object, called Subject.
What does this object “Subject” do:
1.       Registers an observer with itself.
2.       When some special event occurs( special condition is met), it calls observer’s special method.

Interface
Interface is glue that will hold this whole structure together and forms the back bone of this mechanism.
Let the rubber meet the road.

Step 1:
Let’s start by defining an interface.

package com.src.callback.eventInterfaces;

/**
 * Event NumberGreaterThan5Event, action happens
 * when the number is greater than 5.
 *
 * @author Harbir H/ Adofo
 *
 */
public interface NumberGreaterThan5Event {

      /*
       * declaring an event when the number greater than 5
       */
      public abstract void numberGreaterThan5Event();
}


Step 2:
Let’s create an observer that implements the interface “NumberGreaterThan5Event”.

package com.src.callback.call;

import com.src.callback.eventInterfaces.NumberGreaterThan5Event;

/**
 * The class Observer represent the observer building block
 * of the Observer pattern.
 * The name "Observer" depicts the purpose of this class in
 * context with  the Observer Pattern.
 * @author Harbir H/ Adofo
 *
 */
public class Observer implements NumberGreaterThan5Event {

      @Override
      public void numberGreaterThan5Event() {
            System.out
                        .println("Observer: I know that you have entered number greater than 5");
      }
}

Step3:
Let’s create a subject that will call a method on the observer when an event occurs i.e. when a special condition is met.  In other words subject will notify the observer.
 
package com.src.callback.notifier;

import com.src.callback.eventInterfaces.NumberGreaterThan5Event;

/**
 * The class Subject represent the subject building block
 * of the Observer pattern.
 * The name "Subject" depicts the purpose of this class in
 * context with the Observer Pattern.
 *
 * @author Harbir H/ Adofo
 *
 */
public class Subject {

   private NumberGreaterThan5Event numberGreaterThan5Event;

      /*
       * will accept the objects that will implement NumberGreaterThan5Event
       *
       * @param numberGreaterThan5Event
       */
      public Subject(NumberGreaterThan5Event numberGreaterThan5Event) {
            /*
             * initializing the numberGreaterThan5Event or registering the object
             * that implements NumberGreaterThan5Event
             */
            this.numberGreaterThan5Event = numberGreaterThan5Event;

      }

      public void getNum(int num) {
            if ((num >= 5) && (num <= 9)) {
                  /*
                   * special event has occurred, i.e. we have received a number that
                   * is greater than 5
                   */
                  numberGreaterThan5Event.numberGreaterThan5Event();
            }
      }
}

  • Observer does not have to know about the Subject, unless the Observer is registering itself with the Subject.  We will use another class to run our little call back application and register the Observer with the Subject.
  • Subject will only notify the observers that are registered with it.

 
Step 4:
Creating  the CallBack main class, that runs our little call back application.

package com.src.callback.runner;

import java.util.Scanner;

import com.src.callback.call.Observer;
import com.src.callback.notifier.Subject;
/**
 * CallBackApp demonstrates the implementation
 * of the call back method (Observer  Pattern).  
 * Registers the observer with the subject.
 *
 * @author Harbir H/ Adofo
 *
 */
public class CallBackApp {
      private static Observer observer;
      private static Subject subject;
      private static boolean conti = true;
      private static Scanner scanner;

      public static void main(String[] args) {
            observer = new Observer();
            subject = new Subject(observer); // Registering the observer with
                                                                  // subject.

            scanner = new Scanner(System.in);// to input the data
            enterData();
      }

      public static void enterData() {
            System.out.println(" In the Runner do Something");
            do {
                  System.out.println(" Enter the Value:");
                  int val = scanner.nextInt();
                  subject.getNum(val); // information is being sent to the subject. If
                                                      // the condition is met the notification
                                                      // will be sent.
            } while (conti);
      }

}


2 comments:

  1. Great work.

    The essence of the Observer Pattern is to "Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.".

    You have explained it nicely with an example.

    ReplyDelete
  2. The whole concept of observer pattern explained in a simple and elegant manner.

    ReplyDelete