Observer Pattern

PUBLISHED: 2026-07-21
AUTHOR: MANUEL PRIETO
Design Patterns

Observer (or Pub/Sub) is a behavioral design pattern that lets an object (the subject or publisher) notify other objects (the observers or subscribers) about changes in its state without tightly coupling their classes.

Purpose and Use Case

Use the Observer pattern when a change to the state of one object requires changing other objects, and you don't know in advance how many objects need to change. It promotes adherence to the Single Responsibility Principle (SOLIDGlosarioSOLIDAcrónimo de cinco principios de diseño orientado a objetos y programación diseñados para hacer que el software sea más comprensible, flexible y mantenible: S - Single Responsibility Principle (Responsabilidad Única) O - Open/Closed Principle (Abierto/Cerrado) L - Liskov Substitution Principle (Sustitución de Liskov) I - Interface Segregation Principle (Segregación de Interfaz) D - Dependency Inversion Principle (Inversión de Dependencias) Ver término completo →) and keeps code decoupled (KISSGlosarioKISS (Keep It Simple, Stupid)Principio de diseño que establece que la mayoría de los sistemas funcionan mejor si se mantienen simples en lugar de hacerlos complejos. Se debe evitar la complejidad innecesaria en la arquitectura y el código.Ver término completo →).

Unlike creational patterns such as the Singleton Pattern or Factory Method Pattern, Observer manages dynamic runtime communication.

Pattern Structure

  1. Subject (Publisher): Emits events of interest and maintains a list of subscribers to notify them.
  2. Observer (Subscriber): Interface declaring the update method (update).
  3. Concrete Observers: Implementations that react to notifications sent by the publisher.
Cargando diagrama...

Execution Flow

  1. Subscription: Observer objects register with the subject via .subscribe(observer).
  2. Event: A state change occurs in the subject (e.g., new order placed).
  3. Notification: The subject iterates through its internal subscriber list and invokes the .update(data) method on each observer.

Real Implementation Examples