JavaScript – Composite Pattern

GitHub Code

In this post I will be talking about the Composite pattern.  In a nutshell, this item (as I understand) is a structural (reference #1) pattern that builds a complex object by parts.  Similar in concept to the Builder pattern, but different in implementation.  The Builder pattern abstracts the creation of a complex object by adding parts and allowing the composite object to be called at anytime. It uses a single array to keep track of its ‘parts’.

The Composite pattern does this as well…kinda.  The difference is that the Composite pattern can have multiple levels while the Builder only allows one.  Put another way, the Builder is a one level tree and the Composite is an actual tree.

To run:
▪    Make GET call
Screen Shot 2017-05-22 at 12.54.18 PM
▪    Review results

The Screen Shot 2017-05-22 at 12.54.08 PM

The compositeDriver.js runs everything.

Screen Shot 2017-05-22 at 12.54.35 PM

In my implementation, I chose to implement the constituent parts (as defined in reference #1) as follows:

▪    Component – AbsExampleComponent.js – A Component is the blue print for a collection of components that can have sub components.  The definition only includes a method (see reference #1).  However, I chose to include the component management methods as well and have each component inherit from it.  Since inheritance in JavaScript is a little different than C#, each child of AbsExampleComponent.js’s methods are overridden.
Screen Shot 2017-05-22 at 12.54.42 PM
▪    Composite – A Composite (I choose to call my composites components) is the entire object with methods to operate on its components. In my implementation, I choose to directly inherit from AbsExampleComponent.js and override each method and define each property.  There is no file.  Each composite object is created in compositeDriver.js -> createComponentObject(args).
Screen Shot 2017-05-22 at 1.03.23 PM
▪    Leaf – TreeComponent.js – A Leaf is a Composite that cannot have sub composites.  I choose to not have a separate module/object for this, but use a boolean to indicate state on each composite (i.e. isLeaf = true is a leave and isLeaf = false is a regular component).

From the results display, you can see that I added a three level tree.  Level 1 is the root, level 2 is the root’s children and level 3 consists of the root’s grand children (i.e. 7 components in total).

Stay tuned!



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s