Understanding JavaScript Composite Patterns

A composite pattern deals with the complexity of how objects are related to one another. According to the original definition,

[a composite pattern] allows you to compose objects into tree structures to represent part-whole hierarchies

Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley Professional Computing Series)

But what does this mean? Let’s take a look at our cart object again. If we break it down, the entire cart can be composed of many ‘sub-items’ that can also exist as stand-alone items. The cart process involves multiple parts that may or may not be needed, depending on context and situational requirements.

In a composite pattern, an object can have a leaf and/or a composite. A leaf is the object’s implementations while a composite is the child object.

So if you look at it in the form of a tree diagram, a composite pattern looks something like this:

The composite structural pattern keeps the relationships and hierarchies of the objects (composites) together. However, you can take a branch and create ‘part-whole’ objects out of them.

For example, if you take Composite2 and its associated branches, the object created will be a hybrid solution of Composite2 and Composite3. Leaf3 is the actual object methods and properties of Composite2.

So why separate it out and call it a leaf? Why not just have it as part of the composite? Because the composite node itself contains information that helps makes the connection with the child composite. The leaf is a visual representation of the composite’s object.