How would your like your concrete classes to be like an unadorned Christmas tree? When you need an ornament, you put it on. You can put on several of the same type, all different types and when they’re no longer needed, you can take them off. Your central object (class) is unchanged and you’re not processing stuff you’re not using. When you need it; you just pop it on like an ornament on a tree. Further, you can decorate different components with the same ornaments.
When would you use such a pattern? Consider setting up an order form. Each order is an object, and you decorate your order with other objects the user wants to buy. When I buy a computer, I accessorize it with with added memory, a Webcam, a USB hub and anything else that I think I need. However, the store doesn’t have to have a separate computer for every possible combination that users may want to buy. They can just have a few and let the user decorate them anyway she wants. Further, the object you want does not have to drag every option with it—just the ones the buyer wants. You can play the test case and download all of the files using the following two buttons:
The Structure
To kick things off, let’s take a look at the class diagram that the Gang of Four devised. It is one of the most interesting because an abstract class is subclassed from another abstract class (among other things) as can be seen in Figure 1:

Figure 1:Decorator Class Diagram
In looking at what varies, we find that the variation is responsibilities of an object without sub-classing—in other words, use delegation. However, you can see that both the Decorator class and the Concrete Components and Decorators are all sub-classed from Abstract classes. Isn’t that inheritance instead of composition? Of all of the things that can vary in a program structure, those assigned to the Decorator still need further clarification. As you will see in the next section, the Decorator seems to even contradict its own element of variation because it double-subclasses. However, once everything is straightened out, you will find the Decorator example we use to be very simple to implement and even use in a real live work situation.
Continue reading ‘PHP Decorator Design Pattern: Accessorizing Your Classes’
Recent Comments