描述:部分-整体模式,将对象组合成树形结构,单个对象和组合对象使用上一致
优点:调用简单,部分的属性和整体的属性一致,可扩展,易于查找父节点
缺点:抽象的节点需保持近似或一样的属性和方法
应用:遍历组织结构、处理树形结构,比如树形菜单、文件夹管理,组合即树形
classDiagram
class Component {
<>
#name : string
constructor(name : string)
+doOperation()* void
+add(component : Component) void
+remove(component : Component) void
+getChildren() Array
}
class Composite{
-componentList : any;
constructor(name : string)
+doOperation()* void
+add(component : Component) void
+remove(component : Component) void
+getChildren() Array
}
class Leaf{
constructor(name : string)
+doOperation()* void
}
Component <|-- Composite : 继承
Composite o-- Component: 集合
Component <|-- Leaf : 叶子继承
- 抽象构建组件,默认属性和方法
- 树枝节点实现类
- 区别在于多了存储getChildren和管理add/remove子组件
- 叶子节点实现类
- 实例化树枝节点和叶子节点
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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| abstract class Component { protected name : string; constructor(name : string) { this.name = name; } public abstract doOperation() : void; public add(component : Component) : void {} public remove(component : Component) : void {} public getChildren() : Array<Component> { return []; } } class Composite extends Component { private componentList : any; constructor(name : string) { super(name); this.componentList = []; } public doOperation() : void { console.log(`这是容器${this.name},处理一些逻辑业务!`); } public add(component : Component) : void { this.componentList.push(component); } public remove(component : Component) : void { const componentIndex = this.componentList.findIndex((value : Component, index : Number) => { return value == component; }); this.componentList.splice(componentIndex, 1); } public getChildren() : Array<Component> { return this.componentList; } } class Leaf extends Component { constructor(name : string) { super(name); } public doOperation() : void { console.log(`这是叶子节点${this.name},处理一些逻辑业务!`); } } function main() { const root : Component = new Composite('root'); const node1 : Component = new Leaf('1'); const node2 : Component = new Composite('2'); const node3 : Component = new Leaf('3'); root.add(node1); root.add(node2); root.add(node3); const node2_1 : Component = new Leaf("2_1"); node2.add(node2_1); const children1 = root.getChildren(); console.log(children1); root.remove(node2); const children2 = root.getChildren(); console.log(children2); } main();
|