Monday, April 1, 2013

Design Patterns - Decorator Pattern

Introduction

A design pattern is a specific way of solving a particular problem. They are not simply about reusing code; they are more abstract and generalized than that. They are about using reusing ideas.

The Decorator Pattern

The two concrete widgets created for the observer pattern have a different appearance. If you needed to add a new style of widget, you would subclass Widget and implement the draw() method to write the HTML. Say that needed to add a feature to all existing widgets, such as border. You could go into each draw() method and add some more HTML to each, but then the border would be hard-coded and all widgets would be forced to have a border. You could create a new set of subclasses of existing concrete widgets that implemented the border in the draw() method. If you had only two widgets, as in the Observer example, this might be an option - you would end up with four widgets. However, if you had five widgets to start with, it might not seem so appealing. Suddenly you have a lot of widget classes to worry about.

There is another way to handle situations like this, one that doesn't require you to create a new subclass for every widget you want to add a border to. Using the decorator pattern allows you to add features or functionality to existing objects without using inheritance. Next figure shows the class diagram for the decorator pattern.

The class diagram indicates that Decorators are a type of Widget, too. This is good because we don't want to change the way we access a Widget, whether it's decorated or not.

All text and images above is from the book:"Professional PHP5" ISBN: 0-7645-7282-2 (Lecky-Thompson et al., 2005)

1 comment:

  1. Amazing things here. I'm very happy to peer your post. Thank you so
    much and I'm having a look forward to contact you.
    Will you please drop me a e-mail?

    Also visit my web site home remodel contractors; ,

    ReplyDelete