Design Patterns Reference: Decorator

“The Decorator Design Pattern is best suited for altering or decorating portions of an existing object’s content or functionality without modifying the structure of the original object.”

class CD
{
public $trackList;

public function __construct()
{
$this->trackList = array();
}

public function addTrack($track)
{
$this->trackList[] = $track;
}

public function getTrackList()
{
$output = “”;

foreach ($this->trackList as $num=>$track){
$output .= ($num + 1) . “) {$track}. “;
}
}
}

/**
* cd object use
*/

$tracksFromExternalSource = array(‘What It Means’, ‘Brr’, ‘Goodbye’);
$myCD = new CD();
foreach ($trackFromExternalSource as $track){
$myCD->addTrack($track);
}
print “The CD contains the following tracks: ” . $myCD->getTrackList;

/**
* aha, but now the requirements change on us…
* now all tracks need to display uppercase!
* Instead of modifying the original class,
* or changing the parent-child relationships for such small “living requirements”…
* we use the Decorator design pattern!
*/

class CDTrackListDecoratorCaps
{
private $__cd;

public function __construct(CD $cd)
{
$this->__cd = $cd;
}

public function makeCaps()
{
foreach ($this->__cd->trackList as &$track)
{
$track = strtoupper($track);
}
}
}

/**
* new object use
*/

$myCD = new CD();
foreach ($tracksFromExternalSource as $track){
$myCD->addTrack($track);
}
$myCDCaps = new CDTrackListDecoratorCaps($myCD);
$myCDCaps->makeCaps();

print “The CD contains the following tracks: ” . $myCD->getTrackList();

source: http://www.wiley.com/WileyCDA/WileyTitle/productCd-0470496703,descCd-DOWNLOAD.html

Comments are closed.