Created
March 9, 2022 00:26
-
-
Save vrogueon/ec2e32cf1297ca3670374cf75d81dc0a to your computer and use it in GitHub Desktop.
Decorator Pattern example in TS
This file contains 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
interface IPrice { | |
calculate(input: number): number; | |
} | |
class BasePrice implements IPrice { | |
calculate(input: number): number { | |
return input; | |
} | |
} | |
abstract class PriceDecorator implements IPrice { | |
protected price: IPrice; | |
protected discountAmount: number; | |
protected tax: number; | |
constructor(price: IPrice) { | |
this.price = price; | |
} | |
calculate(input: number): number { | |
return this.price.calculate(input); | |
} | |
} | |
class EmployeeDiscountDecorator extends PriceDecorator { | |
discountAmount = 0.4; | |
calculate(input: number): number { | |
input = (input * (1 - this.discountAmount)); | |
return this.price.calculate(input); | |
} | |
} | |
class PromoDiscountDecorator extends PriceDecorator { | |
discountAmount = 0.1; | |
calculate(input: number): number { | |
input = (input * (1 - this.discountAmount)); | |
return this.price.calculate(input); | |
} | |
} | |
class taxDecorator extends PriceDecorator { | |
tax = 1.16; | |
calculate(input: number): number { | |
input = input * this.tax; | |
return this.price.calculate(input); | |
} | |
} | |
const price = new BasePrice(); | |
const employeeDiscount = new EmployeeDiscountDecorator(price); | |
// const promoDiscount = new PromoDiscountDecorator(employeeDiscount); | |
const taxedPrice = new taxDecorator(employeeDiscount) | |
console.log(taxedPrice.calculate(100)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment