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

This commit is contained in:
2026-01-02 01:01:24 +08:00
parent 443e4f2352
commit 4f8d653153
3 changed files with 184 additions and 0 deletions
+63
View File
@@ -0,0 +1,63 @@
/*
实例
汤宝宝教你番茄炒蛋~
*/
class TomatoEgg {
serve() {
console.log("番茄炒蛋上桌啦!")
}
}
class CutTomato {
cut() {
console.log("番茄切好了。");
}
}
class BeatEgg {
beat() {
console.log("鸡蛋打散了。");
}
}
class Cook {
private cutTomato: CutTomato;
private beatEgg: BeatEgg;
constructor() {
this.cutTomato = new CutTomato();
this.beatEgg = new BeatEgg();
}
cookDish() {
this.cutTomato.cut();
this.beatEgg.beat();
console.log("食材放入锅中,开火加热。");
console.log("番茄炒蛋炒好了。");
}
}
// 外观
class ChefFacade {
private tomatoEgg: TomatoEgg;
private cook: Cook;
constructor() {
this.tomatoEgg = new TomatoEgg();
this.cook = new Cook();
}
prepareAndServe() {
console.log("准备食材...")
this.cook.cookDish();
this.tomatoEgg.serve();
}
}
(function(){
console.log("============= 外观模式 =============")
const chef = new ChefFacade();
chef.prepareAndServe();
console.log("\n=========== 外观模式结束 ===========")
})()