Created
January 15, 2024 17:57
-
-
Save evillegas92/b80a10a62ca8d09b48b75bd0a42ddbed to your computer and use it in GitHub Desktop.
TypeScript OOP Polymorphism, Liskov Substitution Principle with Decorator Pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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