Tuesday, October 1, 2024

Observer design Pattern in Java with Real world code Example

Observer design pattern in Java is a fundamental core Java pattern where Observe watches for any change in state or property of Subject. For Example, Company updates all its shareholders for any decision they make here Company is Subject and Shareholders are Observers, any change in the policy of company and the Company notifies all its Shareholders or Observer. This was a simple real-world explanation of the Observer pattern. 

In this article, we will in detail what is Observer Design pattern, what is the benefit of Observer design Pattern, Example or Observer pattern in Java, and few other points. Just like Decorator design Pattern and Factory Pattern in Java, Observer pattern is also used in JDK.


Observer design Pattern Java Code Example

Now, let's deep dive into Observer design Pattern and how to use it in the Java programming language:

Btw, In order to best understand design patterns, you need to work out some scenarios, examples, etc. 

It's best to get this kind of knowledge as part of your work but even if you don't get there, you can supplement them by joining online design pattern courses and doing some object-oriented software design exercises. 


Also here is a nice overview of what is Observer design pattern and how it works before we deep dive into it

Observer design Pattern in Java with Real world code Example



1. What is Observer design Pattern?

Observer design pattern in Java Code ExampleObserver design pattern in Java is a very important pattern and as the name suggests it’s used to observe things. Suppose you want to notify for change in a particular object then you observe that object and changes are notified to you. 

The object which is being observed is refereed as Subject and classes which observe subject are called Observer. 

This is a beautiful pattern and used heavily along with Model View Controller Design pattern where change in model is propagated to view so that it can render it with modified information. 

Observer pattern is also a very popular Java interview questions and mostly asked on Senior or mid senior level.



2. The problem which is solved by Observer Pattern:

If we have requirement that if particular object change its state and subsequently depending upon that some or group of objects automatically change their state we need to implement observer pattern it will reduce coupling between objects.

In real world if try to find example see when we subscribe for new Phone connection whenever customer is registered with that company all other departments are notified accordingly and then depending upon the state they do their jobs like do the verification of their address then if customer state is verified then dispatch the welcome kit etc.



How the Observer Design Pattern is implemented in Java;

For the implementation of this pattern java makes our task very easy, the developer need not do so much for implementing this pattern .In java.util package we can find interfaces, classes, and methods for implementing this pattern.

Public Interface Observer:

Any class that implements this interface must be notified when the subject or observable object changes its status.

Update (Observable Ob, Object arg): This method is called when the subject is changed.


Class Observable:
It’s a subject to whom observer wants to observe.


Some Important Method:
addObserver(Observer o):add Observers in the set of observers for this subject or observalbel object.

deleteObserver(Observer o): delete Observers in the set of observers .

hasChanged():check if object has changed.

clearChanged():this method will indicate that subject has no changes or all the observers has been notified when changes is made.

notifyObservers(): notify all the observers if object has changed .


Code Example of Observer design pattern in Java:

The observer Design pattern is generic than how it is implemented in Java. You are free to choose java.util.Observable or java.util.Observer or writing your own Subject and Observer interface

I prefer having my own Subject and Observer interface and this is how I am going to write my Code Example of Observer design Pattern in java. 

My Example is very Simple you have a Loan on which interest rate is subject to change and when it changes, Loan notifies to Newspaper or Internet media to display a new loan interest rate. 

To implement this we have a Subject interface that contains methods for adding, removing and notifying Observers and an Observer interface which contains update(int interest) method which will be called by the Subject implementation when the interest rate changes.

import java.util.ArrayList;

interface Observer {
       public void update(float interest);
}

interface Subject {
       public void registerObserver(Observer observer);

       public void removeObserver(Observer observer);

       public void notifyObservers();
}

class Loan implements Subject {
       private ArrayList<Observer> observers = new ArrayList<Observer>();
       private String type;
       private float interest;
       private String bank;

       public Loan(String type, float interest, String bank) {
              this.type = type;
              this.interest = interest;
              this.bank = bank;
       }

       public float getInterest() {
              return interest;
       }

       public void setInterest(float interest) {
              this.interest = interest;
              notifyObservers();
       }

       public String getBank() {
              return this.bank;
       }

       public String getType() {
              return this.type;
       }

       @Override
       public void registerObserver(Observer observer) {
              observers.add(observer);

       }

       @Override
       public void removeObserver(Observer observer) {
              observers.remove(observer);

       }

       @Override
       public void notifyObservers() {
              for (Observer ob : observers) {
                     System.out
                                  .println("Notifying Observers on change in Loan interest rate");
                     ob.update(this.interest);
              }

       }

}

class Newspaper implements Observer {
       @Override
       public void update(float interest) {
              System.out.println("Newspaper: Interest Rate updated, new Rate is: "
                           + interest);
       }
}

class Internet implements Observer {
       @Override
       public void update(float interest) {
              System.out.println("Internet: Interest Rate updated, new Rate is: "
                           + interest);
       }
}

public class ObserverTest {

       public static void main(String args[]) {
              // this will maintain all loans information
              Newspaper printMedia = new Newspaper();
              Internet onlineMedia = new Internet();

              Loan personalLoan = new Loan("Personal Loan", 12.5f,
                           "Standard Charterd");
              personalLoan.registerObserver(printMedia);
              personalLoan.registerObserver(onlineMedia);
              personalLoan.setInterest(3.5f);

       }
}


 

Advantage of Observer Design Pattern in Java

The main advantage is loose coupling between objects called observer and observable. The subject only knows the list of observers it don’t care about how they have their implementation. 

All the observers are notified by subject in a single event call as Broadcast communication


Disadvantage of Observer Design Pattern in Java


·          The disadvantage is that the sometime if any problem comes, debugging becomes very difficult because flow of control is implicitly between observers and observable we can predict that now observer is going to fire and if there is chain between observers then debugging become more complex.
·          Another issue is Memory management because subject will hold all the reference of all the observers if we not unregister the object it can create the memory issue.

That’s all on Observer Pattern in Java. It's one of the essential design pattern in object oriented programming and come under behavioral patterns. A good knowledge of this pattern goes a long way in writing better code and also doing well on Java interviews. 

You can also share your thought how and when you have used Observer Pattern in your Project and any issue you have faced?

Further Learning
Design Pattern Library
From 0 to 1: Design Patterns - 24 That Matter - In Java
Java Design Patterns - The Complete Masterclass

Java Tutorials you may like

24 comments:

  1. Thanks for the explanation.It really helps in understanding the Design pattern to its depth.

    There seems to be compilation error in the Main class where you are trying to pass personalLoan.registerObserver(printMedia);
    personalLoan.registerObserver(onlineMedia);

    Newspaper and Internet object but while registering it is expecting Observer Object..

    ReplyDelete
  2. Hi Anonymous, It should not give any compilation error as Internet and NewsPaper both implements observer. I think you might have imported java.util. Observer instead of my custom interface Observer and that causing error. let me know if that's not the case. if you post error , we can take a look.

    ReplyDelete
  3. A good post on observers! But still most developers unaware its very very simple to use observer pattern in JavaEE without implementing those. Of course the app should already be running on a JavaEE server bu that is also easy with the new TomEE and glassfish...
    There is a good tutorial on JavaEE implementation of Observers here:
    http://blogs.eteration.com/blog/?p=1299 and here: http://blogs.eteration.com/blog/?p=1305

    ReplyDelete
  4. You ought to use the Observable/Observer class/interface provided by the jdk because they (for example) consider the setChanged and hasChanged method in the notify observers call.

    Reimplement the pattern when the jdk provides the implementation is source of maintenance problems (new developers must skill on your framework instead on standards) and possible place for bugs.

    My suggestion is to stay closer as possible to the provided API reducing your (i'm sorry) useless sources, just use the jdk when possible.

    ReplyDelete
  5. I would like to add one more weakness: if you have 2 setter calls, you call notify observers twice, that's not so good... the Observable.setChanged call fix this problem,

    anyway nice article... patterns must be spread cause lots of people seems to rely more on antipatterns...

    ReplyDelete
  6. Thanks for your comment morphy, you got it right, setChanged() has its place otherwise it would result it would lead to unnecessary updates to Observable and I also agree that using JDK's Observable/Observer API is good idea, but as learning point of view I see if you understand the pattern by your own example and than compare to what API provides to you.

    ReplyDelete
  7. @Jim , thanks for your comment, yes I agree that most programmer not very familiar with OOPS principle, software designs and design patterns and this is just a little effort to spread the word.

    ReplyDelete
  8. Great article. I finally understood observer pattern. Thank you very much :).

    ReplyDelete
  9. Good Article.Understood observer pattern very well.Thank you.

    ReplyDelete
  10. you! just! made my day. :) This one feels like MVC. but without the views and commands.

    Thanks!

    ReplyDelete
  11. Hi nice article , is it the same thing for example when i post any my status it broadcasted to all people depending on privacy ? can you give any practical example or where we should use it or it is being used ?

    Thanks

    ReplyDelete
  12. Liked the away to explained it, now it's clear to me how observer pattern works :)

    ReplyDelete
  13. Interesting article, but I wanted to query the use of ArrayList for storing observers. This means an observer can be stored more than once. Remove will only remove the first instance of the same observer, in this case. Perhaps using a Set is better?

    ReplyDelete
  14. @Bad Faith, Interesting thought and make sense too. You can use Set in place of ArrayList to store observer, it won't affect the structure of solution.

    ReplyDelete
  15. Hi, good article Javin, this article is to tell us what is the actually structure,flow and glow of "Observer pattern" that's it. How robust one gone going to implement it is there knowledge base. Like one said use Set instead of ArrayList, and change the code of setIntereset() function for efficiency there could be many much more like thread safety, concurrency and all. But that all now up to programmer. Once again thanks @Javin for sharing conceptual knowledge.

    ReplyDelete
  16. @Unknown, you are right. when you write production quality code, you need to think for those aspects. Using Set is certainly a good suggestion to avoid duplicate notification to a subscriber.

    ReplyDelete
  17. very good explanation , but there seems to be an error related to Generics
    child observers can't be added to List , this is against generics because in generics List is not a superset of List , please correct me if i am wrong

    ReplyDelete
  18. This would not scale. How would you change it to add scalability ? A few concerns on top of my head is that many objects can't be stored in out memory in arraylist. Also how can this be parallelized? All the objects need to be notified but are independent of each other. I would love to see an article that solves this problem for large data .

    ReplyDelete
  19. Thanks a lot. This is very very very useful.
    I've been looking for days to understand this pattern. And visited many other sites.
    However I didn't find something more useful than this one.
    Thanks again.

    ReplyDelete
  20. Thank you Anonymous, glad you find my explanation of Observer pattern useful.

    ReplyDelete
  21. that's great! very easy way of explanation. Thanks

    ReplyDelete
  22. Thank you Arun. Glad this article helped you to understand Observer design pattern better.

    ReplyDelete
  23. THanks for your comment Devendra, glad you liked the article.

    ReplyDelete