Composite
Posted by Dustin Boston .
CAUTION
Construction Area
Watch out for:
- Broken code
- No comments
- Partial examples
- Missing tests
Source Code Listing
code.ts
type Component = {
operation(): void;
add(component: Component): void;
getComposite(): Component | undefined;
};
class Leaf implements Component {
operation(): void {
console.log("Leaf operation");
}
add(_component: Component): void {
throw new Error("Cannot add to a leaf");
}
getComposite(): Component | undefined {
return undefined;
}
}
class Composite implements Component {
private readonly list: Component[] = [];
operation(): void {
console.log("Composite operation:");
for (const component of this.list) {
component.operation(); // Delegate to children
}
}
add(component: Component): void {
this.list.push(component);
}
getComposite(): Component {
return this;
}
}
const client = {
run(): void {
const composite = new Composite();
const leaf = new Leaf();
composite.add(leaf);
composite.operation();
const composite2 = new Composite();
composite.add(composite2);
composite.operation();
const composite3 = new Composite();
const leaf2 = new Leaf();
const leaf3 = new Leaf();
composite3.add(leaf2);
composite3.add(leaf3);
composite.add(composite3); // Add a more complex composite
composite.operation();
},
};
client.run();