Java Behavioral Design Patterns – Observer Design Pattern

Observer Design Pattern is listed under Behavioral Design Patterns as it can alter the behavior of the program. In this article, we will understand this pattern with a simple example.

This pattern is chosen when we have one-to-many relationships between objects. Using this pattern will make sure that this relationship is not tightly coupled. When one object changes state, its dependent objects are notified automatically. In short when your application has –

  • A one-to-many dependency between objects and you need to have these objects loosely coupled.
  • You need to have communication between these objects so if the state of one objects is changed, then others are notified.

<Here are ALL other Java Design Patterns, explained in detail with examples>

Observer Design Pattern by Example

The best example to understand this pattern is JMS Topic Subscribe and Publish process. The objects that observe on the state of another object is called Observer and the object that is being watched is called Subject. The subject may provide different methods to an observer.

In our example our Subscribers will be Observer and Topic will be Subject.

First, we will define our abstract class for Observer.

This abstract class will be extended by our topic subscribers. A subscriber is a simple class that has a name and it will attach itself to a particular topic when created.

The subscriber extends Observer and overrides update method.

Topic

The topic class is our subject. It holds the list of observers/subscribers. When a message is published, all the subscribers are notified of it.

Running the Example

Output

Advantages

  • This pattern provides one-to-many relations between objects without tight coupling.
  • This pattern provides very less dependency between Subject and Observer.
  • Observers can be easily added or removed.
  • But at the same time if Observer pattern not used carefully it can add unnecessary complexity to a program.

Conclusion

In this article, we understood Observer Design Patter with the help of a simple example. The source code is available in our Github repository.

Download Code

 

<Here are ALL other Java Design Patterns, explained in detail with examples>

 

Add a Comment

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