实现外观模式示例,添加相关类和方法,增强代码可读性
This commit is contained in:
@@ -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=========== 外观模式结束 ===========")
|
||||
})()
|
||||
Reference in New Issue
Block a user