PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

C H A P T E R 10


■ ■ ■


Patterns for Flexible Object


Programming


With strategies for generating objects covered, we’re free now to look at some strategies for structuring
classes and objects. I will focus in particular on the principle that composition provides greater flexibility
than inheritance. The patterns I examine in this chapter are once again drawn from the Gang of Four
catalog.
This chapter will cover



  • The Composite pattern: Composing structures in which groups of objects can be
    used as if they were individual objects

  • The Decorator pattern: A flexible mechanism for combining objects at runtime to
    extend functionality

  • The Facade pattern: Creating a simple interface to complex or variable systems


Structuring Classes to Allow Flexible Objects


Way back in Chapter 4, I said that beginners often confuse objects and classes. This was only half true. In
fact, most of the rest of us occasionally scratch our heads over UML class diagrams, attempting to
reconcile the static inheritance structures they show with the dynamic object relationships their objects
will enter into off the page.
Remember the pattern principle “Favor composition over inheritance”? This principle distills this
tension between the organization of classes and of objects. In order to build flexibility into our projects,
we structure our classes so that their objects can be composed into useful structures at runtime.
This is a common theme running through the first two patterns of this chapter. Inheritance is an
important feature in both, but part of its importance lies in providing the mechanism by which
composition can be used to represent structures and extend functionality.


The Composite Pattern


The Composite pattern is perhaps the most extreme example of inheritance deployed in the service of
composition. It is a simple and yet breathtakingly elegant design. It is also fantastically useful. Be
warned, though, it is so neat, you might be tempted to overuse this strategy.

Free download pdf