组合模式

组合模式(Composite Pattern),又叫部分整体模式,是用于把一组相似的对象当作一个单一的对象。组合模式依据树形结构来组合对象,用来表示部分以及整体层次。这种类型的设计模式属于结构型模式,它创建了对象组的树形结构。

Graphics.ts

1
2
3
4
5
6
7
8
9
10
11
 export default abstract class Graphics{
name:string;
constructor(name:string){
this.name = name;
}

/**
* 绘制
*/
abstract draw():void;
}

Line.ts

1
2
3
4
5
6
7
8
9
10
11
import Graphics from "./Graphics";

export default class Line extends Graphics{
constructor(name: string){
super(name);
}

draw(){
console.log(this.name+'绘制一条线');
}
}

Circle.ts

1
2
3
4
5
6
7
8
9
10
11
import Graphics from "./Graphics";

export default class Circle extends Graphics{
constructor(name: string){
super(name);
}

draw(){
console.log(this.name+'绘制一个园');
}
}

CompositeGraphics

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import Graphics from "./Graphics";

export default class CompositeGraphics extends Graphics{
graphics: Map<string,Graphics> = new Map();

constructor(name:string){
super(name);
}

draw(){
if(this.graphics.size===0){
console.log('你的复杂图形位增加任何图形');
return;
}
this.graphics.forEach(g=>{
g.draw();
})
}

add(g: Graphics){
const { name } = g;
this.graphics.set(name,g);
}

remove(name: string){
if(this.graphics.has(name)){
this.graphics.delete(name);
}else{
console.log('没有找到相关图形');
}
}

}

index.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import Circle from "./Circle";
import CompositeGraphics from "./CompositeGraphics";
import Line from "./Line"


(function main(){
const l1 = new Line('线1');
const l2 = new Line('线2');
const c1 = new Circle('圆1');
const c2 = new Circle('圆2');
l1.draw();
l2.draw();
c1.draw();
c2.draw();

const com1 = new CompositeGraphics('复杂图形1');
com1.draw();
com1.add(l1);
com1.add(c2);
com1.draw();

})()

输出

1
2
3
4
5
6
7
线1绘制一条线
线2绘制一条线
圆1绘制一个园
圆2绘制一个园
你的复杂图形位增加任何图形
线1绘制一条线
圆2绘制一个园