pattern/gof/builder
- Bun
- TypeScript
Monta um objeto complexo por chamadas nomeadas em qualquer ordem e valida tudo de uma vez em build(), devolvendo todas as violações ou o objeto imutável.
pattern/gof/builder
Cenário
Proposta de R$ 80.000,00 em 48 meses: acima de 24 meses exige garantia de 120% do valor; com garantia a taxa cai de 2,50% para 2,00% a.m.
Planta
Sequência7 passos — reproduza para seguir o fluxo
Como funciona
4passos
Monta um objeto complexo por chamadas nomeadas em qualquer ordem e valida tudo de uma vez em build(), devolvendo todas as violações ou o objeto imutável
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
withX() só grava e devolve o builder
build() roda as regras cruzadas
Violações juntas em ErrorCreditProposalInvalid.violations
Resultado com Object.freeze, garantia inclusa
Trade-offs
O que se ganha, o que se paga
Vantagens
Legível com muitos opcionais
Regras cruzadas num lugar só
Custos
Uma classe a mais por objeto
Erro só aparece no build()
Código
pattern/gof/builder
4 arquivos./
src/
Executar só Bun
bun run demo# roda o cenárioSaída: a proposta sem valor e sem garantia é recusada com as duas violações juntas; a de R$ 80.000,00 em 48 meses com garantia sai congelada a 2,00% a.m.
Código
src/demo.ts// Demo: a credit proposal assembled step by step in any order, validated once in build() and returned frozen.
type Collateral = { readonly type: "vehicle" | "real_estate"; readonly valueCents: number };
type CreditProposal = { readonly amountCents: number; readonly termMonths: number; readonly collateral: Collateral | null; readonly monthlyRateBps: number };
const TERM_MAX_WITHOUT_COLLATERAL = 24;
// The collateral must cover 120% of the amount: the margin absorbs the loss of value in a forced sale.
const COLLATERAL_COVERAGE_PERCENT = 120;
const RATE_BASE_BPS = 250;
const RATE_COLLATERAL_DISCOUNT_BPS = 50;
class ErrorCreditProposalInvalid extends Error {
override name = "ErrorCreditProposalInvalid";
constructor(readonly violations: string[]) {
super(`invalid credit proposal: ${violations.join("; ")}`);
}
}
// Each withX() only stores a value; every cross-field rule runs once, in build(), with all fields known.
class BuilderCreditProposal {
private amountCents = 0;
private termMonths = 0;
private collateral: Collateral | null = null;
withAmount(amountCents: number): this {
this.amountCents = amountCents;
return this;
}
withTerm(termMonths: number): this {
this.termMonths = termMonths;
return this;
}
withCollateral(type: Collateral["type"], valueCents: number): this {
this.collateral = { type, valueCents };
return this;
}
// Every violation at once: the customer fixes the whole form in one go.
build(): CreditProposal {
const violations = [
...(this.amountCents <= 0 ? ["amount is required"] : []),
...(this.termMonths > TERM_MAX_WITHOUT_COLLATERAL && !this.collateral ? [`term above ${TERM_MAX_WITHOUT_COLLATERAL} months requires collateral`] : []),
...(this.collateral && this.collateral.valueCents * 100 < this.amountCents * COLLATERAL_COVERAGE_PERCENT ? [`collateral must cover ${COLLATERAL_COVERAGE_PERCENT}% of the amount`] : []),
];
if (violations.length > 0) throw new ErrorCreditProposalInvalid(violations);
const monthlyRateBps = RATE_BASE_BPS - (this.collateral ? RATE_COLLATERAL_DISCOUNT_BPS : 0);
return Object.freeze({ amountCents: this.amountCents, termMonths: this.termMonths, collateral: this.collateral && Object.freeze({ ...this.collateral }), monthlyRateBps });
}
}
// Same term without collateral and no amount: build() reports both violations at once.
try {
new BuilderCreditProposal().withTerm(48).build();
} catch (error) {
if (!(error instanceof ErrorCreditProposalInvalid)) throw error;
console.log(` [REJECTED] ${error.violations.join("; ")}`);
}
const proposal = new BuilderCreditProposal().withTerm(48).withCollateral("vehicle", 9_600_000).withAmount(8_000_000).build();
console.log(` [CREDIT] R$ ${(proposal.amountCents / 100).toFixed(2)} in ${proposal.termMonths} months, ${proposal.collateral?.type} collateral, ${(proposal.monthlyRateBps / 100).toFixed(2)}% a.m., frozen: ${Object.isFrozen(proposal)}`);
Nível
introdutório
1/13
Padrões do catálogo que implementa
Trilhapasso 3 de 5
GoF — criação
Por que se relacionam
Combina com
Teste rápido
Qual destes combina com Builder?
Monta a consulta passo a passo. Abrir Query Object
Seu progresso
0/157 estudados
Fica salvo só neste navegador.