← Back to home

Observer

By Pscodium · 8/4/2026 · 3 views

Observer

O Observer é um dos padrões comportamentais mais utilizados.

Ele permite que vários objetos sejam notificados automaticamente quando o estado de outro objeto muda.

Temos:

Subject
   │
   ├── Observer A
   ├── Observer B
   └── Observer C

Quando algo muda:

Subject
   │
   ├── Notifica A
   ├── Notifica B
   └── Notifica C

Exemplo

Criamos a interface:

interface Observer {
  update(
    temperature: number
  ): void;
}

O Subject:

class WeatherStation {

  private observers:
    Observer[] = [];

  private temperature = 0;

  subscribe(
    observer: Observer
  ) {
    this.observers.push(
      observer
    );
  }

  unsubscribe(
    observer: Observer
  ) {
    this.observers =
      this.observers.filter(
        item =>
          item !== observer
      );
  }

  setTemperature(
    temperature: number
  ) {
    this.temperature =
      temperature;

    this.notify();
  }

  private notify() {
    for (
      const observer
      of this.observers
    ) {
      observer.update(
        this.temperature
      );
    }
  }
}

Agora temos observers:

class PhoneDisplay
  implements Observer {

  update(
    temperature: number
  ) {
    console.log(
      `Celular: ${temperature}°C`
    );
  }
}
class TVDisplay
  implements Observer {

  update(
    temperature: number
  ) {
    console.log(
      `TV: ${temperature}°C`
    );
  }
}

Podemos registrar:

const station =
  new WeatherStation();

const phone =
  new PhoneDisplay();

const tv =
  new TVDisplay();

station.subscribe(phone);
station.subscribe(tv);

Quando a temperatura muda:

station.setTemperature(
  30
);

Ambos recebem a atualização:

Celular: 30°C
TV: 30°C

Exemplo real: Frontend

O Observer está presente em diversos conceitos de desenvolvimento moderno.

Por exemplo:

Estado muda
    ↓
Componentes são notificados
    ↓
Interface atualiza

Bibliotecas de gerenciamento de estado frequentemente utilizam conceitos semelhantes.

Podemos ter:

Store
 │
 ├── Component A
 ├── Component B
 └── Component C

Quando o estado muda:

Store
 │
 ├── Notifica A
 ├── Notifica B
 └── Notifica C

Outro exemplo são eventos:

eventEmitter.on(
  "userCreated",
  handler
);

Quando o evento acontece:

eventEmitter.emit(
  "userCreated"
);

Todos os listeners registrados podem ser notificados.


Quando usar?

Observer é útil quando:

  • Um objeto precisa notificar vários outros.
  • Queremos reduzir acoplamento.
  • O sistema é orientado a eventos.
  • Precisamos reagir automaticamente a mudanças.

Exemplos:

Eventos
UI
State Management
WebSockets
Event Emitters
Sistemas reativos
Notificações

A ideia principal é:

Permitir que vários objetos observem outro objeto e sejam notificados automaticamente quando seu estado mudar.



Comments

No comments yet.