Composite Pattern - CoffeeScript Design Patterns

Posted on

I recently used the Composite Pattern in a situation where I had to display property panes for hundreds of widgets that were arranged in a tree view. Each widget had their own properties, some could have children. Sound like a daunting task? It was. I typed way too much. But by using the Composite Pattern I got a much more flexible and reusable end-result.

[code lang=“coffee”]

* Declares the interface for objects in the composition.

* Implements default behavior for the interface common # to all classes, as appropriate.

* Declares an interface for accessing and managing its # child components.

* Optionally defines an interface for accessing a # component’s parent in the recursive structure, and # implements it if that’s appropriate.

class Component
constructor: () ->
@list = [L]
getComposite: () ->
operation: () ->
add: (component) ->

  1. * Represents leaf objects in the composition. A leaf
  2. has no children.
  3. * Defines behavior for primitive objects in the composition.

class Leaf extends Component

  1. * Defines behavior for components having children.
  2. * Stores child components
  3. * Implements child-related operations in the
  4. Component interface.

class Composite extends Component
add: (component) ->
@list.push component
operation: () ->
console.log @list
getComposite: () ->
@
[/code]

Usage:

[code lang=“coffee”] # Manipulates objects in the composition through # the Component interface.
class Client
@run: () ->

Create a Composite object and add a Leaf

composite = new Composite()
leaf = new Leaf()
composite.add leaf
composite.operation()

  1. Add a Composite to the Composite

composite2 = new Composite() composite.add composite2 composite.operation()
[/code]