Decorator
Problématique
Comment ajouter des fonctionnalités à une classe sans passer par l’héritage?
Solution
require_once 'polygone.class.php' ; require_once 'parallelogramme.class.php' ; require_once 'rectangle.class.php' ; require_once 'carre.class.php' ; class PolygonColor { private $p ; private $color ; function __construct(Polygone $p) { $this->p = $p ; } function __call($name, $param) { return call_user_func_array( array( $this->p, $name) , $param) ; } public function getColor() { return $this->color ; } public function setColor($red, $green, $blue) { $this->color['red'] = $red ; $this->color['green'] = $green ; $this->color['blue'] = $blue ; } } class PolygonColorFormater { private $p ; function __construct(PolygonColor $p) { $this->p = $p ; } public function getColor() { $color = $this->p->getColor() ; return sprintf( '#%X%X%X', $color['red'], $color['green'], $color['blue'] ) ; } function __call($name, $param) { return call_user_func_array( array( $this->p, $name) , $param) ; } } $rectangle = new PolygonColorFormater(new PolygonColor( new Rectangle(5,2) )) ; echo $rectangle->aire() ; $rectangle->setColor(50, 30, 78) ; var_dump($rectangle->getColor()) ;