pattern/gof/decorator
- Bun
- PostgreSQL
- TypeScript
- node-postgres
- Docker
Acrescenta comportamento por composição: o decorador implementa a mesma interface, envolve o serviço e age antes de delegar. Evita uma subclasse por combinação.
pattern/gof/decorator
Cenário
O serviço grava transferências no PostgreSQL; no canal com tarifa, um decorador soma 2,5% ao valor.
Planta
Classes3 passos — reproduza para seguir o fluxo
Como funciona
4passos
Acrescenta comportamento por composição: o decorador implementa a mesma interface, envolve o serviço e age antes de delegar
Esconde cada passo: lembre antes de tocar para revelar.
ServicePaymentPostgres só grava a transferência
DecoratorPaymentFee implementa a mesma interface e guarda o serviço envolvido
Calcula a tarifa em centavos e delega com o valor acrescido
A composição ocorre em tempo de execução
Trade-offs
O que se ganha, o que se paga
Vantagens
Combina comportamentos sem subclasse
Uma responsabilidade por decorador
Custos
Muitas camadas dificultam o debug
A ordem do empilhamento importa
Código
pattern/gof/decorator
7 arquivos./
sql/
src/
Executar com Docker
./docker.shuntil docker exec decorator-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 decorator-dbSaída: transferência sem decorador grava R$ 1.000,00; com DecoratorPaymentFee grava R$ 1.025,00.
Código
src/demo.ts// Demo: a fee decorator wraps the PostgreSQL payment service at runtime, with the same interface and no subclass.
import pg from "pg";
interface InterfacePaymentService {
transfer(accountFromId: string, accountToId: string, amountCents: number): Promise<void>;
}
// The real component: persists the transfer and nothing else.
class ServicePaymentPostgres implements InterfacePaymentService {
constructor(private readonly pool: pg.Pool) {}
async transfer(accountFromId: string, accountToId: string, amountCents: number): Promise<void> {
await this.pool.query("INSERT INTO transfers (account_from_id, account_to_id, amount_cents) VALUES ($1, $2, $3)", [accountFromId, accountToId, amountCents]);
}
}
// Same interface, wraps the service and charges the fee before delegating; basis points keep the math in integer cents.
class DecoratorPaymentFee implements InterfacePaymentService {
constructor(
private readonly service: InterfacePaymentService,
private readonly feeBasisPoints: number,
) {}
async transfer(accountFromId: string, accountToId: string, amountCents: number): Promise<void> {
const feeCents = Math.round((amountCents * this.feeBasisPoints) / 10_000);
await this.service.transfer(accountFromId, accountToId, amountCents + feeCents);
}
}
const pool = new pg.Pool({ connectionString: Bun.env.DECORATOR_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/decorator_pattern_db" });
await pool.query("TRUNCATE transfers");
const servicePayment = new ServicePaymentPostgres(pool);
await servicePayment.transfer("ACC-1001", "ACC-2001", 100_000);
// Composed at runtime: the same instance, wrapped only for the channel that charges a 2.5% fee.
const FEE_CHANNEL_BPS = 250;
await new DecoratorPaymentFee(servicePayment, FEE_CHANNEL_BPS).transfer("ACC-1001", "ACC-2001", 100_000);
const { rows } = await pool.query<{ amount_cents: string }>("SELECT amount_cents FROM transfers ORDER BY created_at");
console.log(` [BARE] R$ ${(Number(rows[0]!.amount_cents) / 100).toFixed(2)}`);
console.log(` [DECORATED] R$ ${(Number(rows[1]!.amount_cents) / 100).toFixed(2)} (2.5% fee)`);
await pool.end();
Nível
intermediário
4/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 4 de 7
GoF — estrutura
Por que se relacionam
Teste rápido
Qual destes combina com Decorator?
O kit envolve a chamada em camadas. Abrir Resilience Kit
Seu progresso
0/157 estudados
Fica salvo só neste navegador.