Decorator Pattern - CoffeeScript Design Patterns

By on

I use the decorator pattern a lot. There are many implementations in both CoffeeScript and Javascript, but I prefer the classical approach used in the GoF Design Patterns book.

[code lang=“coffee”]
class Component
props: {}
add: (key, val) ->
@props[key] = val
get: () ->
@props
process: () ->

class ConcreteComponent extends Component
process: () ->

class Decorator extends Component
constructor: (@component) ->
process: () ->
@component.process()

class ConcreteDecoratorA extends Decorator
process: () ->
@component.add "concreteDecoratorAProcess", true
super()

class ConcreteDecoratorB extends Decorator
process: () ->
@component.add "concreteDecoratorBProcess", true
super()
[/code]

Usage:

[code lang=“coffee”]
cmpt = new ConcreteDecoratorA new ConcreteDecoratorB new ConcreteComponent()
cmpt.process()

console.log cmpt.get()

[/code]