- Published on
[Structural] Composite
- Authors
- Name
- Khánh
Problems
- How to connect a group of objects to structured objects (which has relationships)?
Bridge pattern
- A method to group objects to structured objects
Tree is a data structure focus on saving and retrieving data. In the meantime, Composite purpose to create a structure for each object.
Steps:
- Create Component interface which determine all actions of nodes
- Init NodeClass (node of Component)
- Init Composite class (group of components)
- Init and asign node classes
Examples:
- Init Component
interface IComponent {
operation(): void;
add(child: IComponent): void;
remove(child: IComponent): void;
getChild(index: number): IComponent | undefined;
}
- Init node
class Leaf implements IComponent {
constructor(public name: string) {}
operation(): void {
console.log(`Leaf operation ${this.name}`);
}
add(child: IComponent): void {
throw new Error("Method not implemented.");
}
remove(child: IComponent): void {
throw new Error("Method not implemented.");
}
getChild(index: number): IComponent | undefined {
return undefined;
}
}
- Init Composite
class Composite implements IComponent {
children: IComponent[] = [];
constructor(public name: string) {}
operation(): void {
console.log(`Operation on ${this.name}`);
for (const child of this.children) {
child.operation();
}
}
add(child: IComponent): void {
this.children.push(child);
}
remove(child: IComponent): void {
const index = this.children.indexOf(child);
if (index !== -1) {
this.children.splice(index, 1);
}
}
getChild(index: number): IComponent | undefined {
return this.children[index];
}
}
- Assign node into Composite
const root = new Composite("Root");
const leaf1 = new Leaf("Leaf 1");
const leaf2 = new Leaf("Leaf 2");
const composite = new Composite("Composite1");
const leaf3 = new Leaf("Leaf 3");
const leaf4 = new Leaf("Leaf 4");
- Retrieve data
root.add(composite);
root.add(leaf1);
root.add(leaf2);
composite.add(leaf3);
composite.add(leaf4);
console.log(root.operation());
Conclusions
- Make a structure for nodes that is not have relationships before
- Can integrate for multiple different nodes
- Easier to maintain