Pular para o conteúdo
  1. Atlas
  2. GoF

Observer

O Subject muda de estado e notifica os observers registrados sem conhecê-los; handler novo entra por subscribe.

passos
4
arquivos
7
testes
0
tecnologias
5

Cenário

Crédito de R$ 1.500,00 na conta avisa a auditoria e a notificação; o ledger só conhece InterfaceObserver.

Planta

Sequência
3/3
UPDATE saldo1update(event): grava audit_log2update(event): avisa o cliente3LedgerAccount (Subject)PostgreSQLObserverAuditObserverNotification
3

3 passos — reproduza para seguir o fluxo

Como funciona

4passos

O Subject muda de estado e notifica os observers registrados sem conhecê-los

Esconde cada passo: lembre antes de tocar para revelar.

  1. 1

    LedgerAccount guarda os observers registrados por subscribe

  2. 2

    O crédito atualiza o saldo no PostgreSQL

  3. 3

    Gravado, chama update(event) de cada observer

  4. 4

    ObserverAudit grava audit_log; ObserverNotification avisa o cliente

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Produtor não conhece quem escuta

  • Novo handler sem tocar no produtor

Custos

  • Ordem e falha dos observers implícitas

  • Notificação síncrona atrasa o produtor

Código

pattern/gof/observer

7 arquivos

./

  • .env.exampleinfra
  • docker.shinfra
  • package.jsoninfra
  • README.md
  • tsconfig.jsoninfra

sql/

  • 01_schema.sqlschema

src/

  • demo.tsdemo

Executar com Docker

  1. ./docker.sh
  2. until docker exec observer-db pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; do sleep 1; done
  3. bun install# dependências
  4. bun run demo# roda o cenário
  5. docker rm -f observer-db

Saída: a auditoria grava o crédito de R$ 1.500,00 em audit_log e a notificação avisa o saldo de R$ 1.500,00.

Requisitos
BunDocker
Sobe junto
PostgreSQL

Código

src/demo.ts

// Demo: the account ledger (subject) commits a credit and notifies its observers without knowing them.
import pg from "pg";

interface InterfaceTransactionEvent {
  accountId: string;
  amountCents: number;
  balanceCents: number;
}

const brl = (cents: number) => `R$ ${(cents / 100).toFixed(2)}`;

interface InterfaceObserver {
  update(event: InterfaceTransactionEvent): Promise<void>;
}

class LedgerAccount {
  private readonly observers: InterfaceObserver[] = [];

  constructor(private readonly pool: pg.Pool) {}

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

  // Observers hear about the transaction only after it is committed.
  async credit(accountId: string, amountCents: number): Promise<void> {
    const { rows } = await this.pool.query<{ balance_cents: string }>("UPDATE accounts SET balance_cents = balance_cents + $1 WHERE id = $2 RETURNING balance_cents", [amountCents, accountId]);
    const event = { accountId, amountCents, balanceCents: Number(rows[0]!.balance_cents) };
    for (const observer of this.observers) await observer.update(event);
  }
}

class ObserverAudit implements InterfaceObserver {
  constructor(private readonly pool: pg.Pool) {}

  async update(event: InterfaceTransactionEvent): Promise<void> {
    await this.pool.query("INSERT INTO audit_log (event_type, account_id, amount_cents) VALUES ('account.credit', $1, $2)", [event.accountId, event.amountCents]);
    console.log(`  [AUDIT] credit ${event.accountId} ${brl(event.amountCents)} logged`);
  }
}

class ObserverNotification implements InterfaceObserver {
  async update(event: InterfaceTransactionEvent): Promise<void> {
    console.log(`  [NOTIFY] ${event.accountId}: credit of ${brl(event.amountCents)}, balance ${brl(event.balanceCents)}`);
  }
}

const pool = new pg.Pool({ connectionString: Bun.env.OBSERVER_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/observer_db" });
const ledger = new LedgerAccount(pool);
// A new handler joins through subscribe, without touching the ledger.
ledger.subscribe(new ObserverAudit(pool));
ledger.subscribe(new ObserverNotification());

await ledger.credit("ACC-001", 150_000);
await pool.end();

Nível

intermediário

5/13

Linhas de TypeScript
43
Tipo
B — um serviço (docker.sh)

Domínio financeiro

  • Crédito/Empréstimo
  • Conta corrente
  • Saldo

Padrões do catálogo que implementa

  • Observer

Infraestrutura

  • PostgreSQLbanco relacional

    postgres:16-alpine:5432

Banco

sql/01_schema.sql

  • accounts
  • audit_log

Variáveis de ambiente

OBSERVER_DATABASE_URL
postgres://postgres:postgres@localhost:5432/observer_db
Accounts database.

Trilhapasso 7 de 11

GoF — comportamento

  1. 1Chain of Responsibility
  2. 2Command
  3. 3Interpreter
  4. 4Iterator
  5. 5Mediator
  6. 6Memento
  7. 7Observer
  8. 8State
  9. 9Strategy
  10. 10Template Method
  11. 11Visitor

Por que se relacionam

Teste rápido

Qual destes combina com Observer?

Próximo projeto, GoFPrototype
Esc

↑ ↓ navegarEnter abrir239 resultados