From 86497cc06bc4cd89f425abdb76a9d06b1f6f5687 Mon Sep 17 00:00:00 2001 From: IvisTang Date: Wed, 31 Dec 2025 17:40:38 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E6=A1=A5=E6=8E=A5=E6=A8=A1?= =?UTF-8?q?=E5=BC=8F=E5=92=8C=E7=BB=84=E5=90=88=E6=A8=A1=E5=BC=8F=E7=A4=BA?= =?UTF-8?q?=E4=BE=8B=EF=BC=8C=E6=B7=BB=E5=8A=A0=E7=9B=B8=E5=85=B3=E7=B1=BB?= =?UTF-8?q?=E5=92=8C=E6=96=B9=E6=B3=95=EF=BC=8C=E5=A2=9E=E5=BC=BA=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=E5=8F=AF=E8=AF=BB=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- go/bridge/main.go | 65 +++++++++++++++++++++++++++++++++ go/composite/main.go | 76 +++++++++++++++++++++++++++++++++++++++ python/bridge/main.py | 67 ++++++++++++++++++++++++++++++++++ python/composite/main.py | 73 +++++++++++++++++++++++++++++++++++++ ts/src/bridge/index.ts | 66 ++++++++++++++++++++++++++++++++++ ts/src/composite/index.ts | 59 ++++++++++++++++++++++++++++++ 6 files changed, 406 insertions(+) create mode 100644 go/bridge/main.go create mode 100644 go/composite/main.go create mode 100644 python/bridge/main.py create mode 100644 python/composite/main.py create mode 100644 ts/src/bridge/index.ts create mode 100644 ts/src/composite/index.ts diff --git a/go/bridge/main.go b/go/bridge/main.go new file mode 100644 index 0000000..80e1f6d --- /dev/null +++ b/go/bridge/main.go @@ -0,0 +1,65 @@ +package main + +import "fmt" + +/* +实例 +汤宝宝成为了一个电子画家,但是不同形状的笔刷和不同颜色颜料的组合让他犯了难... +*/ + +// 抽象类 +type Paint interface { + Use() string +} + +type Brush interface { + Draw() +} + +// 具体实现类 +type RedPaint struct{} + +func (r *RedPaint) Use() string { + return "红色颜料" +} + +type BluePaint struct{} + +func (b *BluePaint) Use() string { + return "蓝色颜料" +} + +type RoundBrush struct { + paint Paint +} + +func (r *RoundBrush) Draw() { + fmt.Printf("使用圆形笔刷和%s进行绘图!\n", r.paint.Use()) +} + +type SquareBrush struct { + paint Paint +} + +func (s *SquareBrush) Draw() { + fmt.Printf("使用方形笔刷和%s进行绘图!\n", s.paint.Use()) +} + +// 绘图函数 +func Painting(brush Brush) { + brush.Draw() +} + +func main() { + fmt.Println("============= 桥接模式 =============") + + redPaint := &RedPaint{} + bluePaint := &BluePaint{} + + Painting(&RoundBrush{paint: redPaint}) + Painting(&SquareBrush{paint: redPaint}) + Painting(&RoundBrush{paint: bluePaint}) + Painting(&SquareBrush{paint: bluePaint}) + + fmt.Println("\n=========== 桥接模式结束 ===========") +} diff --git a/go/composite/main.go b/go/composite/main.go new file mode 100644 index 0000000..660d56d --- /dev/null +++ b/go/composite/main.go @@ -0,0 +1,76 @@ +package main + +import "fmt" + +/* +实例 +汤宝宝成为了上市集团老总,他们集团有好多好多家分公司... +*/ + +// 抽象接口 +type Company interface { + // 显示公司名称 + Show(prefix string) + // 开设分公司 + Add(company Company) + // 分公司关门 + Remove(company Company) + // 获取分公司 + GetChild(i int) Company +} + +// 具体实现类 +type ConcreteCompany struct { + name string + children []Company +} + +func (c *ConcreteCompany) Show(prefix string) { + fmt.Print(prefix) + fmt.Println(c.name) + for _, child := range c.children { + child.Show(prefix + "-> ") + } +} + +func (c *ConcreteCompany) Add(company Company) { + c.children = append(c.children, company) + fmt.Printf("在%s下开设了分公司%s\n", c.name, company.(*ConcreteCompany).name) +} + +func (c *ConcreteCompany) Remove(company Company) { + for i, child := range c.children { + if child == company { + c.children = append(c.children[:i], c.children[i+1:]...) + break + } + } + fmt.Printf("在%s下关闭了分公司%s\n", c.name, company.(*ConcreteCompany).name) +} + +func (c *ConcreteCompany) GetChild(i int) Company { + if i < 0 || i >= len(c.children) { + return nil + } + return c.children[i] +} + +func main() { + fmt.Println("============= 组合模式 =============") + + headOffice := &ConcreteCompany{name: "汤氏总公司"} + headOffice.Add(&ConcreteCompany{name: "汤氏A分公司"}) + headOffice.Add(&ConcreteCompany{name: "汤氏B分公司"}) + headOffice.Add(&ConcreteCompany{name: "汤氏C分公司"}) + headOffice.GetChild(0).Add(&ConcreteCompany{name: "汤氏A分公司-子公司1"}) + headOffice.GetChild(0).Add(&ConcreteCompany{name: "汤氏A分公司-子公司2"}) + headOffice.Remove(headOffice.GetChild(2)) + fmt.Println() + headOffice.Show("~ ") + fmt.Println() + headOffice.GetChild(0).Show("~ ") + fmt.Println() + + fmt.Println("=========== 组合模式结束 ===========") + +} diff --git a/python/bridge/main.py b/python/bridge/main.py new file mode 100644 index 0000000..e095570 --- /dev/null +++ b/python/bridge/main.py @@ -0,0 +1,67 @@ +""" +实例 +汤宝宝成为了一个电子画家,但是不同形状的笔刷和不同颜色颜料的组合让他犯了难... +""" + +from abc import ABC, abstractmethod + + +# 抽象类 +class Paint(ABC): + @abstractmethod + def use(self) -> str: + pass + + +class Brush(ABC): + @abstractmethod + def draw(self) -> None: + pass + + +# 具体实现类 +class RedPaint(Paint): + def use(self) -> str: + return "红色颜料" + + +class BluePaint(Paint): + def use(self) -> str: + return "蓝色颜料" + + +class RoundBrush(Brush): + def __init__(self, paint: Paint) -> None: + super().__init__() + self.paint = paint + + def draw(self) -> None: + print("使用圆形笔刷和" + self.paint.use() + "进行绘图!") + + +class SquareBrush(Brush): + def __init__(self, paint: Paint) -> None: + super().__init__() + self.paint = paint + + def draw(self) -> None: + print("使用方形笔刷和" + self.paint.use() + "进行绘图!") + + +# 绘图函数 +def painting(brush: Brush) -> None: + brush.draw() + + +if __name__ == "__main__": + print("============= 桥接模式 =============") + + red_paint = RedPaint() + blue_paint = BluePaint() + + painting(RoundBrush(red_paint)) + painting(SquareBrush(red_paint)) + painting(RoundBrush(blue_paint)) + painting(SquareBrush(blue_paint)) + + print("\n=========== 桥接模式结束 ===========") diff --git a/python/composite/main.py b/python/composite/main.py new file mode 100644 index 0000000..7560519 --- /dev/null +++ b/python/composite/main.py @@ -0,0 +1,73 @@ +""" +实例 +汤宝宝成为了上市集团老总,他们集团有好多好多家分公司... +""" + +from abc import ABC, abstractmethod + + +# 抽象类 +class Company(ABC): + name: str + children: list["Company"] + + @abstractmethod + def show(self, prefix: str) -> None: + pass + + @abstractmethod + def add(self, company: "Company") -> None: + pass + + @abstractmethod + def remove(self, company: "Company") -> None: + pass + + @abstractmethod + def get_child(self, index: int) -> "Company": + pass + + +# 实现类 +class ConcreteCompany(Company): + name: str + children: list[Company] + + def __init__(self, name: str) -> None: + self.name = name + self.children = [] + + def show(self, prefix: str) -> None: + print(f"{prefix}{self.name}") + for child in self.children: + child.show(f"{prefix}-> ") + + def add(self, company: Company) -> None: + self.children.append(company) + print(f"在{self.name}下开设了分公司{company.name}") + + def remove(self, company: Company) -> None: + self.children.remove(company) + print(f"在{self.name}下关闭了分公司{company.name}") + + def get_child(self, index: int) -> Company: + if index < 0 or index >= len(self.children): + raise IndexError("子公司索引超出范围") + return self.children[index] + + +if __name__ == "__main__": + print("============= 组合模式 =============") + + head_office = ConcreteCompany("汤氏总公司") + head_office.add(ConcreteCompany("汤氏A分公司")) + head_office.add(ConcreteCompany("汤氏B分公司")) + head_office.add(ConcreteCompany("汤氏C分公司")) + head_office.get_child(0).add(ConcreteCompany("汤氏A分公司-子公司1")) + head_office.get_child(0).add(ConcreteCompany("汤氏A分公司-子公司2")) + head_office.remove(head_office.get_child(2)) + print("\n") + head_office.show("~ ") + print("\n") + head_office.get_child(0).show("~ ") + print("\n=========== 组合模式结束 ===========") diff --git a/ts/src/bridge/index.ts b/ts/src/bridge/index.ts new file mode 100644 index 0000000..edee675 --- /dev/null +++ b/ts/src/bridge/index.ts @@ -0,0 +1,66 @@ +/* +实例 +汤宝宝成为了一个电子画家,但是不同形状的笔刷和不同颜色颜料的组合让他犯了难... +*/ + +// 抽象类 +interface Paint { + use():string; +} + +interface Brush { + draw(): void; +} + +// 具体实现类 +class RedPaint implements Paint { + use(): string { + return '红色颜料'; + } +} + +class BluePaint implements Paint { + use(): string { + return '蓝色颜料'; + } +} + +class CircleBrush implements Brush { + private paint: Paint; + + constructor(paint: Paint) { + this.paint = paint; + } + draw(): void { + console.log(`使用圆形笔刷和${this.paint.use()}进行绘图!`); + } +} + +class SquareBrush implements Brush { + private paint: Paint; + + constructor(paint: Paint) { + this.paint = paint; + } + draw(): void { + console.log(`使用方形笔刷和${this.paint.use()}进行绘图!`); + } +} + +const painting = (brush: Brush) => { + brush.draw(); +} + +(function(){ + console.log('============= 桥接模式 =============') + + const redPaint = new RedPaint(); + const bluePaint = new BluePaint(); + painting(new CircleBrush(redPaint)); + painting(new SquareBrush(redPaint)); + painting(new CircleBrush(bluePaint)); + painting(new SquareBrush(bluePaint)); + + console.log('\n=========== 桥接模式结束 ===========') + +})() \ No newline at end of file diff --git a/ts/src/composite/index.ts b/ts/src/composite/index.ts new file mode 100644 index 0000000..d2811fc --- /dev/null +++ b/ts/src/composite/index.ts @@ -0,0 +1,59 @@ +/* +实例 +汤宝宝成为了上市集团老总,他们集团有好多好多家分公司... +*/ + +interface Company { + name: string; + children: Company[]; + show(prefix: string): void; + add(company: Company): void; + remove(company: Company): void; + getChild(index: number): Company | undefined; +} + +class ConcreteCompany implements Company { + name: string; + children: Company[] = []; + constructor(name: string) { + this.name = name; + } + show(prefix: string): void { + console.log(prefix + this.name); + for (const child of this.children) { + child.show(prefix + "-> "); + } + } + add(company: Company): void { + this.children.push(company); + console.log(`在${this.name}下开设了分公司${company.name}`); + } + remove(company: Company): void { + const index = this.children.indexOf(company); + if (index !== -1) { + this.children.splice(index, 1); + } + console.log(`在${this.name}下关闭了分公司${company.name}`); + } + getChild(index: number): Company | undefined { + return this.children[index]; + } +} + +(function () { + console.log("============= 组合模式 ============="); + + const headOffice = new ConcreteCompany("总公司"); + headOffice.add(new ConcreteCompany("汤氏A分公司")); + headOffice.add(new ConcreteCompany("汤氏B分公司")); + headOffice.add(new ConcreteCompany("汤氏C分公司")); + headOffice.getChild(0)?.add(new ConcreteCompany("汤氏A分公司-子公司1")); + headOffice.getChild(0)?.add(new ConcreteCompany("汤氏A分公司-子公司2")); + headOffice.remove(headOffice.getChild(2)!); + + console.log(); + headOffice.show("~ "); + console.log(); + headOffice.getChild(0)?.show("~ "); + console.log("\n=========== 组合模式结束 ==========="); +})();