1
0
Fork 0

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

This commit is contained in:
IvisTang 2026-01-02 01:01:24 +08:00
parent 443e4f2352
commit 4f8d653153
3 changed files with 184 additions and 0 deletions

72
go/facade/main.go Normal file
View File

@ -0,0 +1,72 @@
package main
import (
"fmt"
)
/*
实例
汤宝宝教你番茄炒蛋~
*/
type TomatoEgg struct{}
func (t *TomatoEgg) Serve() {
fmt.Println("番茄炒蛋上桌啦!")
}
type CutTomato struct{}
func (c *CutTomato) Cut() {
fmt.Println("番茄切好了。")
}
type BeatEgg struct{}
func (b *BeatEgg) Beat() {
fmt.Println("鸡蛋打散了。")
}
type Cook struct {
cutTomato *CutTomato
beatEgg *BeatEgg
}
func (c *Cook) CookDish() {
c.cutTomato.Cut()
c.beatEgg.Beat()
fmt.Println("食材放入锅中,开火加热。")
fmt.Println("番茄炒蛋炒好了。")
}
// 外观
type ChefFacade struct {
cook *Cook
dish *TomatoEgg
}
func NewChefFacade() *ChefFacade {
return &ChefFacade{
cook: &Cook{
cutTomato: &CutTomato{},
beatEgg: &BeatEgg{},
},
dish: &TomatoEgg{},
}
}
func (c *ChefFacade) PrepareAndServe() {
fmt.Println("准备食材...")
c.cook.CookDish()
c.dish.Serve()
}
func main() {
fmt.Println("============= 外观模式 =============")
chef := NewChefFacade()
chef.PrepareAndServe()
fmt.Println()
fmt.Println("=========== 外观模式结束 ===========")
}

49
python/facade/main.py Normal file
View File

@ -0,0 +1,49 @@
"""
实例
汤宝宝教你番茄炒蛋~
"""
class TomatoEgg:
def serve(self):
print("番茄炒蛋上桌啦!")
class CutTomato:
def cut(self):
print("番茄切好了!")
class BeatEgg:
def beat(self):
print("鸡蛋打好了!")
class Cook:
cutTomato: CutTomato
beatEgg: BeatEgg
def __init__(self,cutTomato: CutTomato, beatEgg: BeatEgg) -> None:
self.cutTomato = cutTomato
self.beatEgg = beatEgg
def cook_dish(self):
self.cutTomato.cut()
self.beatEgg.beat()
print("食材放入锅中,开火加热。")
print("番茄炒蛋炒好了。")
# 外观
class ChefFacade:
cook: Cook
dish: TomatoEgg
def __init__(self) -> None:
self.cook = Cook(CutTomato(), BeatEgg())
self.dish = TomatoEgg()
def prepare_and_serve(self):
print("准备食材...")
self.cook.cook_dish()
self.dish.serve()
if __name__ == "__main__":
print("============= 外观模式 =============")
chef = ChefFacade()
chef.prepare_and_serve()
print("\n=========== 外观模式结束 ===========")

63
ts/src/facade/index.ts Normal file
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=========== 外观模式结束 ===========")
})()