pattern/gof/observer
- Bun
- PostgreSQL
- TypeScript
- node-postgres
- Docker
O Subject muda de estado e notifica os observers registrados sem conhecê-los; handler novo entra por subscribe.
pattern/gof/observer
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ência3 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.
LedgerAccount guarda os observers registrados por subscribe
O crédito atualiza o saldo no PostgreSQL
Gravado, chama update(event) de cada observer
ObserverAudit grava audit_log; ObserverNotification avisa o cliente
Trade-offs
O que se ganha, o que se paga
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./
sql/
src/
Executar com Docker
./docker.shuntil docker exec observer-db pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; do sleep 1; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f observer-dbSaí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.
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
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
PostgreSQLbanco relacional
postgres:16-alpine:5432
Banco
sql/01_schema.sql
Variáveis de ambiente
Trilhapasso 7 de 11
GoF — comportamento
Por que se relacionam
Teste rápido
Qual destes combina com Observer?
O mesmo aviso, agora entre serviços. Abrir Event Notification
Seu progresso
0/157 estudados
Fica salvo só neste navegador.