1
0
Fork 0

Compare commits

...

2 Commits

6 changed files with 465 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("=========== 外观模式结束 ===========")
}

102
go/flyweight/main.go Normal file
View File

@ -0,0 +1,102 @@
package main
import "fmt"
/*
实例
汤宝宝开了一家服装租赁店好多客人来店里租衣服~
*/
// 享元对象 - 服装
type Clothing struct {
style string
size string
color string
}
func (c *Clothing) Show() {
fmt.Printf("服装款式:%s尺码%s颜色%s\n", c.style, c.size, c.color)
}
// 享元工厂 - 服装店
type ClothingFactory struct {
clothingPool map[string]*Clothing
}
func NewClothingFactory() *ClothingFactory {
return &ClothingFactory{
clothingPool: make(map[string]*Clothing),
}
}
func (f *ClothingFactory) GetClothing(style, size, color string) *Clothing {
key := style + "-" + size + "-" + color
if clothing, exists := f.clothingPool[key]; exists {
return clothing
}
newClothing := &Clothing{style: style, size: size, color: color}
f.clothingPool[key] = newClothing
return newClothing
}
func (f *ClothingFactory) ShowStock() {
fmt.Println("\n服装库存")
for key, clothing := range f.clothingPool {
fmt.Printf("Key: %s -> ", key)
clothing.Show()
}
}
// 客人
type Customer struct {
name string
clothing []*Clothing
}
func NewCustomer(name string) *Customer {
return &Customer{
name: name,
clothing: []*Clothing{},
}
}
func (c *Customer) RentClothing(clothing *Clothing) {
fmt.Printf("%s 租了一件服装: ", c.name)
clothing.Show()
c.clothing = append(c.clothing, clothing)
}
func (c *Customer) ShowClothing() {
fmt.Printf("\n客人%s租赁的服装有\n", c.name)
for _, cloth := range c.clothing {
cloth.Show()
}
}
func main() {
fmt.Println("============= 享元模式 =============")
factory := NewClothingFactory()
// 客人1租衣服
customer1 := NewCustomer("小红")
customer1.RentClothing(factory.GetClothing("连衣裙", "M", "红色"))
customer1.RentClothing(factory.GetClothing("牛仔裤", "L", "蓝色"))
// 客人2租衣服
customer2 := NewCustomer("小明")
customer2.RentClothing(factory.GetClothing("连衣裙", "M", "红色")) // 共享同一件连衣裙
customer2.RentClothing(factory.GetClothing("西裤", "S", "白色"))
fmt.Println()
// 显示租赁情况
customer1.ShowClothing()
customer2.ShowClothing()
// 显示服装库存
factory.ShowStock()
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=========== 外观模式结束 ===========")

83
python/flyweight/main.py Normal file
View File

@ -0,0 +1,83 @@
"""
实例
汤宝宝开了一家服装租赁店好多客人来店里租衣服~
"""
class Clothing:
"""享元对象 - 服装"""
style: str
size: str
color: str
def __init__(self, style: str, size: str, color: str):
self.style = style
self.size = size
self.color = color
def show(self):
print(f"服装款式: {self.style}, 尺码: {self.size}, 颜色: {self.color}")
class ClothingFactory:
"""享元工厂 - 服装店"""
_clothing_pool: dict[str, Clothing]
def __init__(self):
self._clothing_pool = {}
def get_clothing(self, style: str, size: str, color: str) -> Clothing:
key = f"{style}-{size}-{color}"
if key not in self._clothing_pool:
self._clothing_pool[key] = Clothing(style, size, color)
return self._clothing_pool[key]
def show_stock(self):
print("\n服装库存:")
for key, clothing in self._clothing_pool.items():
print(f"Keys: {key} -> ", end="")
clothing.show()
class Customer:
name: str
clothing: list[Clothing]
def __init__(self, name: str):
self.name = name
self.clothing = []
def rent_clothing(self, clothing: Clothing):
self.clothing.append(clothing)
print(f"{self.name} 租了一件服装: ", end="")
clothing.show()
def show_clothing(self):
print(f"\n客人{self.name} 租赁的服装有:")
for clothing in self.clothing:
clothing.show()
if __name__ == "__main__":
print("============= 享元模式 =============")
factory = ClothingFactory()
# 客人1租衣服
customer1 = Customer("小红")
customer1.rent_clothing(factory.get_clothing("连衣裙", "M", "红色"))
customer1.rent_clothing(factory.get_clothing("牛仔裤", "L", "蓝色"))
# 客人2租衣服
customer2 = Customer("小明")
customer2.rent_clothing(factory.get_clothing("连衣裙", "M", "红色"))
customer2.rent_clothing(factory.get_clothing("西裤", "S", "白色"))
print()
# 显示租赁情况
customer1.show_clothing()
customer2.show_clothing()
# 显示服装库存
factory.show_stock()
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=========== 外观模式结束 ===========")
})()

96
ts/src/flyweight/index.ts Normal file
View File

@ -0,0 +1,96 @@
/*
~
*/
// 享元对象 - 服装
class Clothing {
private style: string;
private size: string;
private color: string;
constructor(style: string, size: string, color: string) {
this.style = style;
this.size = size;
this.color = color;
}
show() {
console.log(
`服装款式: ${this.style}, 尺码: ${this.size}, 颜色: ${this.color}`
);
}
}
// 享元工厂 - 服装店
class ClothingFactory {
private clothingPool: { [key: string]: Clothing };
constructor() {
this.clothingPool = {};
}
getClothing(style: string, size: string, color: string): Clothing {
const key = `${style}-${size}-${color}`;
if (!this.clothingPool[key]) {
this.clothingPool[key] = new Clothing(style, size, color);
}
return this.clothingPool[key];
}
showStock() {
console.log("\n服装库存:");
for (const key in this.clothingPool) {
console.log(`Key: ${key} ->`);
this.clothingPool[key].show();
}
}
}
// 客人
class Customer {
private name: string;
clothing: Clothing[];
constructor(name: string) {
this.name = name;
this.clothing = [];
}
rentClothing(clothing: Clothing) {
console.log(`${this.name} 租了一件服装.`);
this.clothing.push(clothing);
clothing.show();
}
showClothing() {
console.log(`\n客人${this.name}租赁的服装有:`);
this.clothing.forEach((c) => c.show());
}
}
(function () {
console.log("============= 享元模式 =============");
const factory = new ClothingFactory();
// 客人1租衣服
const customer1 = new Customer("小红");
customer1.rentClothing(factory.getClothing("连衣裙", "M", "红色"));
customer1.rentClothing(factory.getClothing("牛仔裤", "L", "蓝色"));
// 客人2租衣服
const customer2 = new Customer("小明");
customer2.rentClothing(factory.getClothing("连衣裙", "M", "红色")); // 共享同一件连衣裙
customer2.rentClothing(factory.getClothing("夹克", "XL", "黑色"));
console.log();
// 显示租赁情况
customer1.showClothing();
customer2.showClothing();
// 显示服装库存
factory.showStock();
console.log("\n=========== 享元模式结束 ===========");
})();