Article Image
read

Recently, I have become interested obsessed with design patterns.  What caused the spark of excitement was that I was working on an algorithm similar to one of the patterns (I can't remember which) when I read Head First Design Patterns and realized it had already been created for me! By the way, I'd recommend Head First, it's a great learning series.

Also, I use the term "class" for "component" and "method" for "function". So without further ado,  my first article on implementing design patterns in Coldfusion.

Decorator Pattern

A decorator more or less wraps a base class and well...decorates it. This can be useful when you have a scenario that would need a lot of classes to cover all of the possible combinations of objects.

My Implementation

I followed the example by Hal Helms as far as the class organization is concerned.  Some of the decorators are me being funny (piglatin and mirror), but I can see some value in the TableDecorator, JsonDecorator and XmlDecorator.

Let me explain each file a bit more.

  • Test.cfm
    • Instantiates the components and outputs results

  • Person.cfc
    • Base class (whose methods will be overridden by the decorators)
  • PersonDecorator.cfc
    • Base decorator class (all decorators for Person will inherit from this class)
  • PersonJsonDecorator.cfc
    • Creates a JSON representation of a Person.
  • PersonXmlDecorator.cfc
    • Creates a XML representation of a Person by wrapping the elements with nodes that represent each element
  • PersonTableDecorator.cfc
    • Creates a table representation of a Person by wrapping elements with <td>'s and the entire Person with <tr>

Links

Source Files

Wikipedia's Page on Decorators

Hal Helm's Decorator Article

Blog Logo

Jon Dowdle

Jon Dowdle currently works on the internet at a lovely place called InVision.


Published

Color

Jon Dowdle's Blog

The personal blog of Jon Dowdle.

Back to Overview