I was reading a programming article and it mentioned the Decorator pattern. I've been programming for awhile but without any kind of formal education or training, but I'm trying to learn about the standard patterns and such. So I looked up the Decorator, and found a Wikipedia article on it. I now understand the concept of the Decorator pattern, but I was a bit confused by this passage:
As an example, consider a window in a windowing system. To allow scrolling of the window's contents, we may wish to add horizontal or vertical scrollbars to it, as appropriate. Assume windows are represented by instances of the Window class, and assume this class has no functionality for adding scrollbars. We could create a subclass ScrollingWindow that provides them, or we could create a ScrollingWindowDecorator that adds this functionality to existing Window objects. At this point, either solution would be fine.
Now let's assume we also desire the ability to add borders to our windows. Again, our original Window class has no support. The ScrollingWindow subclass now poses a problem, because it has effectively created a new kind of window. If we wish to add border support to all windows, we must create subclasses WindowWithBorder and ScrollingWindowWithBorder. Obviously, this problem gets worse with every new feature to be added. For the decorator solution, we simply create a new BorderedWindowDecorator—at runtime, we can decorate existing windows with the ScrollingWindowDecorator or the BorderedWindowDecorator or both, as we see fit.
OK, when they say to add borders to all windows, why not just add functionality into the original Window class to allow for the option? The way I see it is, subclassing is just for adding specific functionality to a class, or overriding a class method... If I needed to add functionality to all existing objects, why wouldn't I just modify the superclass to do so?
There was another line in the article:
The decorator pattern is an alternative to subclassing. Subclassing adds behavior at compile time, and the change affects all instances of the original class; decorating can provide new behavior at run-time for individual objects.
I don't get where they say "...the change affects all instances of the original class" -- how does subclassing change the parent class? Isn't that the whole point of subclassing?
I'm going to assume that the article, like many Wiki's, is just not written clearly. I can see the usefulness of the Decorator in that last line - "...provide new behavior at run-time for individual objects." Without having read about this pattern, if I needed to change behavior at run-time for individual objects, I would have probably built some methods into the super- or subclass to enable/disable said behavior... can someone help me really understand the usefulness of the Decorator, and why my newbie thinking is flawed?
thanks so much!!