Introduction to Observer Pattern

In this article we are going to learn about Observer patter. What is observer pattern? What are the basic principle? How can we implement that? Where we can use that and example. I am going to use java-eclipse and c#-vs2010 for example.

What is Observer pattern?
By the name we can understand that observer is a behavioral pattern defines the state of observable.. In object module design, when we need to observe an object by other objects, we can apply this observer pattern. It means, it can be used in a problem domain where monitoring is involved. And, the object which will be monitored called subject object and the observer objects will monitor. A state of the subject will be reported to monitors.
For example, suppose we are designing a payment system. So, we have to monitor the transaction in every stage of operation, we need to monitor changes of a client object and process according to the state(like as messaging, emailing, logging, error handling, load balancing on server or massive hit)

Or, if you are designing email system. When an email is read, the state needs to be notified to server.

In out testing world, we need this pattern in very crucial way. Suppose we are designing reporting system, and we need to report/log state of the object after a certain time or any change of the object. I even use that as trigger for another set of operation on change of the subject(object).

It is also a part of MVC (architectural) pattern. 

Target :
Establish one to many dependency between objects that will allow one object's change state to be notified/updated automatically to all dependent objects .

UML : (I have applied slide differently)
 
How to implement?
From the definition, we see that we need
- A observable class which object will be observed(the subject)
- observers , who will monitor or get the state or get notified of the state of the observable.

So, to implement a observable class, we will apply in generic way.
1. An Interface or abstract that reflect the observable behavior
2. A simple class that implements/inherits that interface or abstract class. This will contain state representing data members.

Like same way, in case of Observers, we will have
1. An Interface or abstract that reflect the observer behavior

2. A simple class that implements/inherits that interface or abstract class. 

So, what will be in the observable Interface? Our target is to notify all observers. So, a method should be their to satisfy that.
public abstract class MyObservable {    
    public void notifyAllOvservers(){        
    }
}

This is just basic function. Usually, we need some extra functionality for better relation with observers. Like, adding, deleting , counting observers and own state situation.


public abstract class MyObservable {
    private List<MyObserver> observers = new ArrayList<MyObserver>();
    public void notifyAllOvservers(){
        for(int i=0; i<observers.size();i++){
            observers.get(i).update();
        }
    }
    public void notifyAllOvservers(Object arg){
    //Just another way to notify with arguments
        for(int i=0; i<observers.size();i++){
            observers.get(i).update(arg);
        }        
    }
    public void attachAObserver(MyObserver observer) {
        observers.add(observer);
    }
    public void detachAObserver(MyObserver observer) {    
        observers.remove(observer);
    }
    public int countObservers(){
        return observers.size();        
    }
    protected abstract void setChange();
    protected abstract void clearChange();
    protected abstract void hasChange();
    public MyObservable(){                
    }
}

So, If we want to make any object as observable, we just extend this class. And the state will be defined depend on problem domain, i.e- if we keep state as count, every change of state means change of the value. Or, if we keep that as any object, the member value of the object will define the state of the subject like as stock. 
Note : java 1.7 have java.util.Observable class used with MVC. We extend this for a class which we want to observe.

[ If we use interface, that should be like following 


public interface IMyObservable {
    void notifyAllOvservers();
    void notifyAllOvservers(Object arg);
    void attachAObserver(MyObserver observer);   
    void detachAObserver(MyObserver observer);
    int countObservers();
    void setChange();
    void clearChange();
    void hasChange();
}

And we have to add MyObserver List in implementing class.

I have kept those state describing method in the class, you can omit those from abstract class and add in implementation class only.
]
Now, Let's make an observer. By principle, we need simply a function to notify it self. I use two type of update.


public abstract class MyObserver {
    public abstract void update();
    public abstract void update(Object args);//another way to notify
}

[If we use Interface, It will be


public interface IMyObserver {
   void update();
   void update(Object args);
}

]
Note : java 1.7 have java.util.Observer Interface used with MVC. We implement this for a class which we want to make it observer.

-In both observer and observable, I use parametrize update method so that , in case if we want to specify object's(subject) update(it self).
-From the structure, we see, a subject will notify all observers. Sometime in real life scenario, the subject changes so frequently that the process will consume more time to notify all observers. In that cases, we can share the notify all method to observers so that it can notify all others.
- Now, think about when to notify, I mean which state of subject. usually, when the object is consistent(no operation is running, or no dependencies in run time) the change of the object should be notifies(it will be safe).
- In real life we can either push(subject provide info to observers) or pull(observers takes info from subject)method. But, for efficiency, push is mostly used. And some time used categorize. A conditional observation can be applied. For example : if there is a large data to express state, then if we try to notify all observer, it might make very slow. What we do, we apply small type , like notify only change occurs, if any observer need to know details, he can pull the changes. This way we can make our design efficient. Another way is , categorize observers like some observer will get small info of changes , some will get detail of the changes(if necessary)

Java Example : I have updated the structure only. 
Let's think about a problem. I was looking at a problem found for practice. The problem says, suppose there is a new agency let say BBC. BBC gets news from its different sources. BBC has subscribers who get the news update based on any news change. They get update via SMS/mail/RSS feed, or any updated way(should be extendable as new technology brings new way of communication). In here, lets think what are the main classes.
BBC/News Agency
Subscribers/Who get notified of the updates
News/which are maintain by the news agency.
So, lets apply Observer pattern.
BBC(or the news agency) will apply the observable.
And the Subscribers will be the observers.
The NEWS will be the data that are monitored by the agency to notify.(notify condition/checking)

C# Example : I have updated the structure only.
1. You will find some method changes as dot net implementation has small differences. 

Uses : 
- Distributed Event handling system (spatially DotNet, and swing)
- When change state of an object needed to be reflected to another object. (and keep it loos coupled)
- When we need to implement monitor type functions/enhancements over legacy code.

Thanks...:)

No comments:

Post a Comment