This example illustrates the structure of the Decorator design pattern and focuses on the following questions:
- What classes does it consist of?
- What roles do these classes play?
- In what way the elements of the pattern are related?
interface Component { public function operation(): string; }Let's create a class called Decorator.php and let it be implemented by Component.php. The Decorator delegates all work to the wrapped component.
class Decorator implements Component { protected $component; public function __construct(Component $component) { $this->component = $component; } public function operation(): string { return $this->component->operation(); } }Let's also create a Concrete Component and have implemt the Component.php class. We call our compnent ConcreteDecoratorA. Decorators may call parent implementation of the operation, instead of calling the wrapped object directly. This approach simplifies extension of decorator classes.
class ConcreteDecoratorA extends Decorator { public function operation(): string { return "ConcreteDecoratorA(" . parent::operation() . ")"; } }Let's now create a ConcreteDecoratorB.php class file. Like ConcreteDecoratorA it too is exteded with the Decorator.php class
class ConcreteDecoratorB extends Decorator { public function operation(): string { return "ConcreteDecoratorB(" . parent::operation() . ")"; } }Let's now goto the index.php file at the top we have the includes.
include_once ('Component.php'); include_once ('ConcreteComponent.php'); include_once ('Decorator.php'); include_once ('ConcreteDecoratorA.php'); include_once ('ConcreteDecoratorB.php');The client code works with all objects using the Component interface. This way it can stay independent of the concrete classes of components it works with.
function clientCode(Component $component) { // ... echo "RESULT: " . $component->operation(); // ... }This way the client code can support both simple components as well as decorated ones.
$simple = new ConcreteComponent; echo "Client: I've got a simple component:<br/>"; clientCode($simple); echo "<br/><br/>";Note how decorators can wrap not only simple components but the other decorators as well.
$decorator1 = new ConcreteDecoratorA($simple); $decorator2 = new ConcreteDecoratorB($decorator1); echo "Client: Now I've got a decorated component:When we view the the index.php through a browser you should get:
"; clientCode($decorator2);
Client: I've got a simple component: RESULT: ConcreteComponent Client: Now I've got a decorated component: RESULT: ConcreteDecoratorB(ConcreteDecoratorA(ConcreteComponent))
The Ray Code is AWESOME!!!
wikipedia
Find Ray on:
youtube
The Ray Code
Ray Andrade