Design Patterns In Java – Observer By Example

In this design patterns in java series, I will be documenting the most common design patterns as written by the Gang of Four in their classic book: Design Patterns – Elements of Reusable Object-oriented Software.

I will maintain a pattern (no pun intended) of giving a real-world example then show you the code example. Ready? Let us do this!

design patterns java

Real World Example

Design patterns are everywhere in our lives. For example, a newspaper publishing company releases papers each morning and the papers are delivered to their customers/readers by the good old paper boys! So, the company will keep a list of newspaper subscribers in their database somewhere! The readers are free to subscribe to or unsubscribe from the service if you are tired or when money runs out! Makes sense right?

Observer Design Pattern Example

In our example, we will have a newspaper publisher as our Subject and the readers as Observers.

Our Subjects will implement this interface!

Our Observers will implement this interface!

Our Subject will look something like this:

Then our sample Observer class will look like this:

To finally test our design pattern, we need a main method like you would for an entry point into a Java application!

So, in summary, the idea is to let the Subject notify all the Observers (Publisher/Subscriber) whenever a new paper has been printed or released!

You can always view the code used in this example on github!

I hope this tutorial helped you get an idea of how the Observer design pattern works in a general sense of things.

Please share and subscribe (again, no pun intended here) to my future posts on design patterns! Remember, I will be covering all 23 here that are commonly mentioned!

Have a great day and see you soon!

Written By Elisha Chirchir

Elisha Chirchir is a software developer. He is also the founder of Simple Developer and co-founder of Instinctive Software Solutions. On any given day, he works on both Android and Web Development. During his 'free time', he offers training to those interested in learning how to code in php, java, python, javaScript etc. You can easily find him on StackOverflow Android chatroom or on Twitter @Eenvincible

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.