Contact Me

Composite

 This pattern allows you to compose objects into tree structures, and treat individual objects and compositions of objects uniformly. This can be useful when you want to represent part-whole hierarchies, and treat both parts and whole objects uniformly.


Here is an example of the composite pattern in JavaScript:


class Component {

constructor(name) {

  this.name = name;

}

add(component) {}

remove(component) {}

isComposite() return false;

operation() {}

}

class Leaf extends Component {

operation() {

  console.log(`Leaf operation for ${this.name}.`);

}

}

class Composite extends Component {

constructor(name) {

  super(name);

  this.children = [];

}

add(component) {

  this.children.push(component);

}

remove(component) {

  this.children = this.children.filter(c => c !== component);

}

isComposite() { return true; }

operation() {

  console.log(`Composite operation for ${this.name}.`);

  this.children.forEach(c => c.operation());

}

}

const leaf1 = new Leaf('Leaf 1');

const leaf2 = new Leaf('Leaf 2');

const composite = new Composite('Composite');

composite.add(leaf1);

composite.add(leaf2);

composite.operation();

// Output:

// Composite operation for Composite.

// Leaf operation for Leaf 1.

// Leaf operation for Leaf 2.


In this example, the Component class is an abstract class that defines the structure for a component in the composite, and the Leaf and Composite classes are concrete implementations of the Component class that represent leaves and composites in the composite structure.

The Leaf class has an operation() method that performs an operation specific to leaf objects, and the Composite class has an operation() method that performs an operation specific to composite objects, as well as calling the operation() method on each of its children.

To use the composite pattern, we create instances of the Leaf and Composite classes and add them to the composite structure by calling the add() method on the composite object. Then, when we want to perform an operation on the composite, we call the operation() method on the root of the composite structure.

This will recursively call the operation() method on all of the objects in the composite, treating both leaves and composites uniformly.