PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 10 ■ PATTERNS FOR FLEXIBLE OBJECT PROGRAMMING

Figure 10–4. More hard-coded variations


What happens, though, when you need to perform logging and authentication but not data
preparation? Do you create a LogAndAuthenticateProcessor class? Clearly, it is time to find a more
flexible solution.


Implementation


Rather than use only inheritance to solve the problem of varying functionality, the Decorator pattern
uses composition and delegation. In essence, Decorator classes hold an instance of another class of their
own type. A Decorator will implement an operation so that it calls the same operation on the object to
which it has a reference before (or after) performing its own actions. In this way it is possible to build a
pipeline of decorator objects at runtime.
Let’s rewrite our game example to illustrate this:


abstract class Tile {
abstract function getWealthFactor();
}


class Plains extends Tile {
private $wealthfactor = 2;
function getWealthFactor() {
return $this->wealthfactor;
}
}


abstract class TileDecorator extends Tile {
protected $tile;
function __construct( Tile $tile ) {
$this->tile = $tile;
}
}

Free download pdf