Wednesday, March 24, 2010

Tonight's Design Pattern - The Matryoshka Doll

The commonly accepted name for the pattern I just read about is the Decorator Pattern. The idea is that you decorate your objects with responsibilities and you do this by "wrapping" them in classes with the same interface. So if you're decorating a couch object with wooden feet, custom fabric, and a fold out bed then you end up creating this Russian Matryoshka Doll system of a thing inside a thing inside a thing inside a thing.

To me, it's kind of a shitty pattern. To use it as described, you have some interface that the couch implements, but then so do the wooden feet, the bed, and the fabric. Those other things, in the examples I've seen and can thing of, don't  really share some common set of behavior, but the pattern necessitates that they do, so it's an artificial interface. Like putting 60 people in a room and telling them they all enjoy golf.

It's also a bit of crap because of this crazy wrapping. If you get a base object that has ten responsibilities tacked on, then you've got to drill down ten layers to see what the hell is going on in this code of yours. However! What you get out of it is the ability to add these responsibilities at run time as opposed to design/compile time, which is pretty cool. Also, you cut down on class-explosions. The big OO win here is that the classes are closed to change, but remain open for extension. So Boris can come along and add functionality to my class without changing a lick of my code.

No comments: