This is a comment I had about an article on the Decorator pattern

I think some people may overlook the importance/usefulness of the decorator pattern since all you’re doing in the examples could be accomplished by just concatenating P and /P around the getData() wherever it is you were going to display it.

I find the decorator pattern is best for when you have a lot of parts to the data that need a lot of manipulation of their values and a lot of html but not so much html that it warrants a full page/template/view.

For example in my (poorly written) real estate site I have an object that represents a property for sale in the listings table of the DB. All 126 fields of the property record!

When it’s time to show info about the property to a visitor I only need to show them about a dozen fields. But most of those fields need to be manipulated. I need to ucfirst() the property status text, convert the price to Euros/Pounds/USD/BSD, attach the http://www.site.com/listings/… onto the permalink text of the listing, convert 3.5 into “3 1/2 Bath”, convert the square feet values into Acres if they are over 1 acres in size and lots of other stuff. Also all these fields had to be wrapped in html tags and ids and css classes etc.

At first I had all that stuff as part of the code that happens _before_ the data is saved to the database. Then other clients came along who wanted the same system (but different) and I realized a lot of those manipulations were only relevant to the site visitors. So then I put those instructions in the main class file as $listing->displayOverview() method.

But then some more clients came along who wanted something other than the default set of info in the default format. Some clients wanted the category value to link to a search results page of everything in that category. Some wanted the neighbourhood value to do the same. Some didn’t want the category or neighbourhood value to be shown. Sure I could have just use css to hide the neighbourhood span but some high end clients don’t want anyone to know where their house is located so the neighbourhood/address values weren’t allowed to be anywhere in the markup. They had to be taken out at the code level.

It unfortunately took a looong time and a lot of clients on this system to realize I needed to take this segment of my code and turn it into a custom decorator for each client that needed one.

Before that realization, at one point I had a site identifier variable and a ton of IF statements strewn throughout the code that made it a nightmare to read!

For another good example of decorator usage see this Zend Framework Zend_Form screencast (requires having a zend.com account).

, ,

  1. No comments yet.
(will not be published)