Monday, June 8, 2009

Design Pattern: Decorator

Decorator is similar to Proxy.
Basically, decorator is an extension (or wrapper) of the original class (component) and adds features.
A decorator contains a pointer to the component class (initialized by the constructor), and the methods of the component overridden.

Example:


class ImgComponent {
private $src;
private $alt;
public function __construct($name, $src) { /* assign to properties*/ };
public function getHTML() {
return "[ img src="{$this->src}\" alt=\"{$this->alt}\" /]";
}
}

Let's write a decorator:


class ImgWithCaption extends imgComponent
{
private $caption;
private $imgComponent;
public function __construct(&$img, $caption) {
$caption->imgComponent = $caption;
$this->imgComponent = &$img;
};

public function getHTML() {
return "<div><div>{parent::getHTML()}</div>
<div> $caption</div></div>";
}
}

No comments:

Post a Comment

 

PHP and tips|PHP