Design Pattern | Observer Pattern
What Is the Observer Pattern?
- Observer means one who observes.
- The Observer pattern notifies observers when the state of the observed subject changes.
- It is effective when describing processing that depends on state changes.
- It registers observers of an object’s state changes in a list, and whenever the state changes, the object directly notifies each observer through methods.
- It is mainly used to implement distributed event handling systems and is also known as the publish/subscribe model.
- In GoF design patterns, it is classified as a behavioral design pattern.
Observer Pattern Example Program
This example program randomly generates numbers and displays numbers and * according to the changes.
Class Diagram

The example defines an Observer interface, a generator that notifies observers, and concrete observers that display the generated value in different ways.
Advantages
The subject and observers are loosely coupled. New observers can be added without changing the subject, and multiple reactions can be attached to one state change.