实现桥接模式和组合模式示例,添加相关类和方法,增强代码可读性

This commit is contained in:
2025-12-31 17:40:38 +08:00
parent 64cc579e42
commit 86497cc06b
6 changed files with 406 additions and 0 deletions
+66
View File
@@ -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=========== 桥接模式结束 ===========')
})()
+59
View File
@@ -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=========== 组合模式结束 ===========");
})();