实现策略模式和模板方法模式示例,添加支付策略和烹饪流程,增强代码可读性

This commit is contained in:
2026-01-07 19:27:14 +08:00
parent 5fbbada4b7
commit e5be1b62c2
6 changed files with 268 additions and 0 deletions
+48
View File
@@ -0,0 +1,48 @@
/*
实例:
汤宝宝成为了收银员,消费者可以使用现金或者支付宝支付。
*/
interface Strategy {
pay(amount: number): string;
}
class CashStrategy implements Strategy {
pay(amount: number): string {
return `使用现金支付了${amount.toFixed(2)}元`;
}
}
class AlipayStrategy implements Strategy {
pay(amount: number): string {
return `使用支付宝支付了${amount.toFixed(2)}元`;
}
}
class Context {
private strategy: Strategy| null = null;
setStrategy(strategy: Strategy) {
this.strategy = strategy;
}
pay(amount: number): string {
if (!this.strategy) {
throw new Error("支付策略未设置");
}
return this.strategy.pay(amount);
}
}
(function(){
console.log("=========== 策略模式 ===========")
const context = new Context();
context.setStrategy(new CashStrategy());
console.log(context.pay(100));
context.setStrategy(new AlipayStrategy());
console.log(context.pay(200));
console.log("\n========= 策略模式结束 =========")
})()
+34
View File
@@ -0,0 +1,34 @@
/*
实例:
汤宝宝炒西红柿鸡蛋。
*/
abstract class Dish {
abstract prepareIngredients(): string;
abstract cook(): string;
abstract serve(): string;
doCooking(): void {
console.log("第一步:", this.prepareIngredients());
console.log("第二步:", this.cook());
console.log("第三步:", this.serve());
}
}
class TomatoEggs extends Dish {
prepareIngredients(): string {
return "准备西红柿和鸡蛋;";
}
cook(): string {
return "炒西红柿和鸡蛋;";
}
serve(): string {
return "装盘,西红柿鸡蛋炒好了。";
}
}
(function(){
console.log("========== 模板方法模式 ==========");
const dish = new TomatoEggs();
dish.doCooking();
console.log("\n======== 模板方法模式结束 ========");
})()