DEV Community

Determinado 96
Determinado 96

Posted on

Um resumo sobre o padrão de projeto Decorator

Definição

É um padrão de projeto estrutural que permite adicionar comportamentos ou responsabilidades a um objeto de forma dinâmica sem mudar a classe original.

Analogia

Imagine que temos uma classe simples chamada Café. Agora precisamos de Café com leite, Café com açucar, Café com leite e açucar, Café com leite, açucar e chantilly.

Um solução ruim seria criar uma explosão de classes:

CafeComLeite
CafeComAcucar
CafeComLeiteEAcucar
CafeComLeiteEAcucarEChantilly
...

O decorator resolve isso permitindo empilhar funcionalidades:

Café

  • Leite
    • Açúcar
      • Chantilly

Exemplo de implementação do decorator

interface Coffee {
  getDescription(): string;
  getCost(): number;
}

class SimpleCoffee implements Coffee {
  getDescription(): string {
    return 'Café';
  }

  getCost(): number {
    return 5;
  }
}

abstract class CoffeeDecorator implements Coffee {
  constructor(protected coffee: Coffee) {}

  getDescription(): string {
    return this.coffee.getDescription();
  }

  getCost(): number {
    return this.coffee.getCost();
  }
}

class MilkDecorator extends CoffeeDecorator {
  getDescription(): string {
    return this.coffee.getDescription() + ', Leite';
  }

  getCost(): number {
    return this.coffee.getCost() + 2;
  }
}

class SugarDecorator extends CoffeeDecorator {
  getDescription(): string {
    return this.coffee.getDescription() + ', Açúcar';
  }

  getCost(): number {
    return this.coffee.getCost() + 1;
  }
}

// Uso

let coffee: Coffee = new SimpleCoffee();

coffee = new MilkDecorator(coffee);
coffee = new SugarDecorator(coffee);

console.log(coffee.getDescription());
console.log(coffee.getCost());

Enter fullscreen mode Exit fullscreen mode

Top comments (0)