Skip to content

Instantly share code, notes, and snippets.

@vrogueon
Created March 9, 2022 00:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vrogueon/ec2e32cf1297ca3670374cf75d81dc0a to your computer and use it in GitHub Desktop.
Save vrogueon/ec2e32cf1297ca3670374cf75d81dc0a to your computer and use it in GitHub Desktop.
Decorator Pattern example in TS
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