Home » Core Java » Observer Design Pattern

Observer Design Pattern

Observer Design Pattern :: Observer Design Pattern comes under behvioral design pattern.In this design pattern an observer is notified if any changes occur to an object which the observer is subscribed to.

Real Time Example :: Suppose there are serveral readers.One category of readers like to read Java Topics and other set of readers like to read Spring Topics .So these readers(Observers) first subscribes to corresponding SubjectTopic(Subjects).Once any changes to Subject, new articles added to topic and any subscriber is added/removed then if reader/subscriber opts for notification he/she can get the notification about the same.

 

UML Diagram ::

 

Step 1 :
Create an Interface Subject.java and declare methods subscribeObsever(Observer observer),unSubscribeObsever(Observer observer) and notifyAllObsevers() .
subscribeObsever() method adds an Observer/Subscriber.
unSubscribeObsever method removes an Observer/Subscriber.
notifyAllObsevers() method notify all Observers/Subscribers currently subscribed for the Subject.

Step 2 :
Create an Interface Observer.java and declare methods updateObserver() .
updateObserver() method updates an Observer/Subscriber if any changes happen to Subject.
I have also optionally added getName() method to get details about Observer/Subscriber.


Step 3 :
Create a class TopicEnrollment.java which implements interface Subject.java and has its own implementation for methods subscribeObsever(Observer observer),unSubscribeObsever(Observer observer) and notifyAllObsevers() .

Step 4 :
Create a class Subsrciber.java which implements interface Observer.java and has its own implementation for methods updateObserver()nd getName()
I also have an instance of Subject here ,so that a Subscriber can subscribe to corresponding Subject.I am doing the same in the constructor.

Step 5 :
Create main class ObserverDesignPatternDemo.java.I have created two topics “java-8” and “Spring-5” to demo Observer design pattern.

<


Output ::


Leave a comment

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

2 × five =