实现装饰器模式示例,添加相关类和方法,增强代码可读性

This commit is contained in:
2026-01-01 00:41:28 +08:00
parent 29fd3f0557
commit 443e4f2352
3 changed files with 164 additions and 0 deletions
+50
View File
@@ -0,0 +1,50 @@
/*
实例
汤宝宝家有一台咖啡机,他会自动给美式咖啡加奶和糖...
*/
interface Drink {
price: number;
name: string;
cost(): void;
}
class Coffee implements Drink {
price: number;
name: string;
constructor(name: string, price: number) {
this.name = name;
this.price = price;
}
cost() {
console.log(`一杯${this.name}咖啡,价格${this.price.toFixed(2)}元`);
}
}
class Maker {
drink: Drink;
milkPrice: number;
sugarPrice: number;
constructor(drink: Drink, milkPrice: number, sugarPrice: number) {
this.drink = drink;
this.milkPrice = milkPrice;
this.sugarPrice = sugarPrice;
}
cost() {
this.drink.cost();
const total = this.drink.price + this.milkPrice + this.sugarPrice;
console.log(`加奶加糖后,总价${total.toFixed(2)}元`);
}
}
(function(){
console.log("============= 装饰器模式 =============");
console.log("自己泡杯咖啡")
const coffee = new Coffee('美式', 10);
coffee.cost();
console.log("\n用咖啡机泡杯咖啡")
const maker = new Maker(coffee, 1, 1);
maker.cost();
console.log("\n=========== 装饰器模式结束 ===========");
})()