Wednesday, June 22, 2011

Observable and Observers

We need to accept some conventions while developing an application and out of them, MVC is an accepted pattern by many developers because it makes the code easy to understand by isolating the controller portion of the code from view and model.

It is easy to imaging in MVC way, but while implementing we need to face some challenges like:
1) The controller and model are sometimes so tied, it is very difficult or complex to isolate the model from controller.
2) The communication among model,view and controller may not be straightforward.

Here, I will focus the communication part and how java is achieving this in an efficient way. Suppose, we are going to implement notification between two classes Receiver, Sender where Receiver object receives the notification sent by Sender. To implement this, we need to:
i) extend class Observable in Sender class.
ii) implement the Observer interface in Receiver class

The Sender class will be like this:

class Sender extends Observable{
private void doSomeTask(){
//Notify here

The class Receiver will look like this:

class Receiver implements Observer{
//Create observable object
Sender sender;
public Receiver(){
//add the observer object
public void update(Observable observable, Object object){
//check the observable class
//do some job here

The overriden method update of receiver class gets the notification from the observer. The update method takes the Observable object and the object sent from the Obvervable.

i) We can completely separate Model from Controller.
ii) Replaces creation of event handler which is lengthy process and requires more steps.

The one disadvantage is the observable class should be subclass of Observable and since inheritance in java does not allow multiple inheritance. So, if observable class needs to have more than one super class, it is not feasible, we need to change the implementation.