2015-08-13 23:54:40 +02:00
---
layout: pattern
title: Observer
folder: observer
2015-08-15 18:03:05 +02:00
permalink: /patterns/observer/
2015-08-20 21:40:07 +02:00
categories: Behavioral
2016-08-20 20:49:28 +05:30
tags:
2015-09-22 18:25:56 +05:30
- Java
- Difficulty-Beginner
- Gang Of Four
2016-07-21 09:27:48 +03:00
- Reactive
2015-08-13 23:54:40 +02:00
---
2016-01-03 21:14:30 +01:00
## Also known as
Dependents, Publish-Subscribe
2015-11-04 21:13:32 +02:00
2016-01-03 21:14:30 +01:00
## Intent
Define a one-to-many dependency between objects so that when one
2015-08-13 23:54:40 +02:00
object changes state, all its dependents are notified and updated
automatically.
2019-07-29 20:21:07 +02:00

2015-08-13 23:54:40 +02:00
2016-01-03 21:14:30 +01:00
## Applicability
Use the Observer pattern in any of the following situations
2015-08-13 23:54:40 +02:00
* when an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently
* when a change to one object requires changing others, and you don't know how many objects need to be changed
* when an object should be able to notify other objects without making assumptions about who these objects are. In other words, you don't want these objects tightly coupled
2016-01-03 21:14:30 +01:00
## Typical Use Case
2015-08-13 23:54:40 +02:00
* changing in one object leads to a change in other objects
2016-01-03 21:14:30 +01:00
## Real world examples
2015-08-13 23:54:40 +02:00
2015-08-15 18:03:05 +02:00
* [java.util.Observer ](http://docs.oracle.com/javase/8/docs/api/java/util/Observer.html )
2016-08-20 20:49:28 +05:30
* [java.util.EventListener ](http://docs.oracle.com/javase/8/docs/api/java/util/EventListener.html )
* [javax.servlet.http.HttpSessionBindingListener ](http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpSessionBindingListener.html )
2017-05-30 13:22:52 +02:00
* [RxJava ](https://github.com/ReactiveX/RxJava )
2015-09-22 18:25:56 +05:30
2016-01-03 21:14:30 +01:00
## Credits
2015-09-22 18:25:56 +05:30
* [Design Patterns: Elements of Reusable Object-Oriented Software ](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612 )
2016-01-27 12:55:59 +05:30
* [Java Generics and Collections ](http://www.amazon.com/Java-Generics-Collections-Maurice-Naftalin/dp/0596527756/ )