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

Decorator

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.

passos
4
arquivos
7
testes
0
tecnologias
5

Cenário

O serviço grava transferências no PostgreSQL; no canal com tarifa, um decorador soma 2,5% ao valor.

Planta

Classes
3/3
«interface»InterfacePaymentService+transfer(accountFromId, accountToId, amountCents)ServicePaymentPostgresDecoratorPaymentFeedelega
3

3 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.

  1. 1

    ServicePaymentPostgres só grava a transferência

  2. 2

    DecoratorPaymentFee implementa a mesma interface e guarda o serviço envolvido

  3. 3

    Calcula a tarifa em centavos e delega com o valor acrescido

  4. 4

    A composição ocorre em tempo de execução

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

  • .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 decorator-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 decorator-db

Saída: transferência sem decorador grava R$ 1.000,00; com DecoratorPaymentFee grava R$ 1.025,00.

Requisitos
BunDocker
Sobe junto
PostgreSQL

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

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

Domínio financeiro

  • Tarifa

Padrões do catálogo que implementa

  • Decorator

Infraestrutura

  • PostgreSQLbanco relacional

    postgres:16-alpine:5432

Banco

sql/01_schema.sql

  • transfers

Variáveis de ambiente

DECORATOR_DATABASE_URL
postgres://postgres:postgres@localhost:5432/decorator_pattern_db
PostgreSQL holding the transfers.

Trilhapasso 4 de 7

GoF — estrutura

  1. 1Adapter
  2. 2Bridge
  3. 3Composite
  4. 4Decorator
  5. 5Facade
  6. 6Flyweight
  7. 7Proxy

Por que se relacionam

Teste rápido

Qual destes combina com Decorator?

Próximo projeto, GoFFacade
Esc

↑ ↓ navegarEnter abrir239 resultados