Observer Pattern in Java with example.

Let us answer some of the questions related to Observer Pattern in this post that is asked in the core java interview.
What is Observer pattern?
When and why to use this pattern?
How to implement Observer Pattern in java?Now consider the following situation and issues.

     1. When many objects depend on other object, the state change of the other object needs to be updated  to all dependent objects to maintain consistency between these objects.
     2.  At the same time , we need to achieve the above updation by making these objects loosely coupled (de-coupled) which reduces dependency and allows to reuse these objects independently .
     One of the easiest way to notify / update the state change to the dependent objects is to call them directly as given below. But direct calling between objects increases dependency between their objects which can not be reused independently. See the below code , a bad design



      In the above code, NoticeBoard and Employee are dependent. When there is a update in the NoticeBoard, it is updated to all employees who have registered. Employee object is created within updateNoticeBoard or updateNoticeBoard1 method and update method of employee object is called. This direct calling between objects increases dependency. For example, when you change the name of the class Employee, you have to change in all the places where employee object is created in NoticeBoard class.

So the generic solution for the above situations to maintain consistency between related objects and to decrease the dependency between objects, would be the Observer Pattern which is a nice pattern.

Observer Pattern is a commonly used pattern in core java .

Observer pattern involves a subject that has multiple views (observers). Each view object needs to be updated whenever the subject changes or  In other words we can also say that the object containing the data (subject ) is separate from the objects that displays the data (observers ), and these display objects observe changes on that data. These behavior can be seen in some of the real life applications.

 

1. Google Alerts : New user can subscribe for an update on a particular subject in the web , google notifies all subscribers when there is a update on the subject in the web . Existing subscriber can unsubscribe if they don’t wan’t updates.
2. Some application showing TextView and Scroll View of any counter or any other numeric result. Both TextView and Scroll View are observers that observe the data change to update text and graphical view.

3. In excel, average() and sum() function can be dependent on the same data object and therefore the change in the data should be notified to these functions to display the correct result. Both can be reused independantly.

 

This pattern is also called Dependents, Publish-Subscribe, Model-View. Observer Pattern is used with MVC architecture where subject Model plays the role of Subject and the View represents the Observer. MVC pattern helps separation of business data (the model) and the presentation logic (the view). When the model changes, the system must notify the view about the model’s state

Now let us see How to implement Observer Pattern in Java ?
The Observer pattern can be implemented by the built-in Java Observer Pattern using java.util.Observable and java.util.Observer. You can also implement by your own code.
The java.util package provides a built-in implementation of the Observer pattern using the Observable class and Observer interface

interface Observer : (View in the model-view architecture)
An interface which is implemented as observer objects . In other words we can say, an observer is any object that implements interface Observer . This interface contains only one method update which is called by the Observable to update the state change of the Subject (Observable object) to observer objects.

Syntax : void update(Observable o, Object arg);

java.util.Observable : (data in the model-view architecture)

This class represents a Subject which is an observable object. The object needs to have observed has to extend the class Observable . An observable object can have more than one observers. All the list of observers registered / subscribed with Observable object are notified when there is a state change in the Subject.

Some of the methods of Observable Class :
addObserver() : Adds an observer object to the set of observers , where all observer objects in the Set are unique.

clearChanged() : Indicates that the subject has no changes, or that it has already notified all changes to all observers

countObservers() : Returns the number of observers added in the Observable object.

deleteObserver() / deleteObservers() : Removes an observer / all observers from the set of observers

hasChanged() : Returns true if the subject object has any change to be updated to observers.

notifyObservers() : Checks for the change in the Subject (state change in the Observable object), if there is any change ,it is notified to all of its observers then call the clearChanged method to indicate the subject has no changes.

setChanged() : Marks this Observable object as having been changedFirst let us see the code example of Observer Pattern using ready made implementation of Java.

Example 1:
Consider the Notice Board of an organization. NoticeBoard object represents the Subject. Employee can subscribe for the notice board updation. Whenever the notice board is updated, all the employees who have subscribed are notified the change.

Two main classes are created. NoticeBoard class which extends Observable. Employee class which implements observer. Both are related objects and having less dependency . Both objects can be reused independently. NoticeBoard knows about the list of subscribers only and does know about the actual implementation

Output:

Example 2:

              Now let us write code for own implementation of Observer Pattern. For example, Gold / Silver prices are updated on daily basis. People will buy gold / silver when the price is low. People will sell the gold / silver when the price is high. So they need price updation when there is a change in price . For that , they have to subscribe to PriceUpdate (an object being observed). 


Note : 1. Java interface plays a major role in implementation of Observer Pattern.
2. In the above code , Duplicate objects are not accepted . Two different objects with same name will be accepted. Methods like subscribe, unSubscribe and notifyObservers of PriceUpdate class can be synchronized for thread-safe.


Output:

You may also like

Leave a Reply

Be the First to Comment!