observer pattern
behavioral pattern, Java, observer pattern, OOP, Programming, Software Engineering

Design Patterns: Observer

An observer is a pattern that falls under Behavioral Patterns. It is used when there is one-to-many relationships between objects. So, when an object’s state is changed then all its dependent objects are notified automatically.

When do you have to use Observer

  • When a change to one object requires to notify other objects.
  • We don’t need to be aware of how many objects need to be changed.
  • We don’t want these objects tightly coupled.

How to use it

The concept behind the Observer pattern is simple. We have a subject that is going to keep track of the observers. Every time this subject changes, all its observers are notified automatically. The subject contains some methods that allow observers to be registered or unregistered.

When the state of the subject changes then the subject has to notify all the observers which are registered.

This pattern is so flexible that sometimes we want to change this behavior and let observers ask the subject for the state and if it is changed, then the observer acts appropriately.

Example

Let’s suppose that we are at a university and we want to update every student who is registered in a course. If the student is registered in a specific course then every time the state of the course is changed, registered students will receive a notification.

Start with the Subject interface

We will implement the Subject interface.

Let’s create one more interface named Observer

StudentObserver class is going to implement the interface above.

Last but not least StudentObserver we have one more class named Email, and as you can imagine we are going to use this class so as to send emails to students.

Now we are ready to use these classes.

Output:

You can download the source code from GitHub.