Skip to content

Instantly share code, notes, and snippets.

@evillegas92
Created January 15, 2024 17:57
Show Gist options
  • Save evillegas92/b80a10a62ca8d09b48b75bd0a42ddbed to your computer and use it in GitHub Desktop.
Save evillegas92/b80a10a62ca8d09b48b75bd0a42ddbed to your computer and use it in GitHub Desktop.
TypeScript OOP Polymorphism, Liskov Substitution Principle with Decorator Pattern
// POLYMORPHISM
// Liskov Substitution principle with composition and the Decorator Pattern
// source: https://blog.appsignal.com/2022/04/06/principles-of-object-oriented-programming-in-typescript.html
interface Coffee {
getCost(): number;
getIngredients(): string;
}
class SimpleCoffee implements Coffee {
getCost(): number {
return 8;
}
getIngredients(): string {
return "Coffee";
}
}
abstract class CoffeeDecorator implements Coffee {
constructor(private readonly decoratedCoffee: Coffee) { }
getCost() {
return this.decoratedCoffee.getCost();
}
getIngredients() {
return this.decoratedCoffee.getIngredients();
}
}
class WithMilk extends CoffeeDecorator {
constructor(private readonly coffee: Coffee) {
super(coffee);
}
getCost() {
return super.getCost() + 2.5;
}
getIngredients() {
return super.getIngredients() + ", Milk";
}
}
class WithSugar extends CoffeeDecorator {
constructor(private readonly coffee: Coffee) {
super(coffee);
}
getCost() {
return super.getCost() + 1;
}
getIngredients() {
return super.getIngredients() + ", Sugar";
}
}
class WithSprinkles extends CoffeeDecorator {
constructor(private readonly c: Coffee) {
super(c);
}
getCost() {
return super.getCost() + 1.7;
}
getIngredients() {
return super.getIngredients() + ", Sprinkles";
}
}
class Barista {
constructor(private readonly cupOfCoffee: Coffee) {}
orders() {
this.orderUp(this.cupOfCoffee);
let cup: Coffee = new WithMilk(this.cupOfCoffee);
this.orderUp(cup);
cup = new WithSugar(cup);
this.orderUp(cup);
cup = new WithSprinkles(cup);
this.orderUp(cup);
}
private orderUp(coffee: Coffee) {
console.log(`Cost: ${coffee.getCost()}, Ingredients: ${coffee.getIngredients()}`);
}
}
const barista = new Barista(new SimpleCoffee());
barista.orders();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment