Decorator design patter is a structural design patter that provide a means of adding new properties to an object.
How?
Let's look at the component of the this pattern
Main components
- interface (template for the object to be of the same type)
- Class to Decorate that implements the interface
- class that decorate(decorator) is and abstract class the implements the interface
Auxiliary components
- class that inherit decorator class
interface BuidingConcern{
function addComponent($what);
function removerComponent();
}
class House implements BuidingConcern{
/////////class to decorate
function addComponent($what){
return ' has added '. $what;
}
function removerComponent(){
}
}
abstract class Worker implements BuidingConcern{
//class that decorate
protected BuidingConcern $house ; ///protect so that childeren class can access it
function __construct(BuidingConcern $houseToBuild){
$this->house = $houseToBuild;
}
abstract function addComponent($toadd);
abstract function removerComponent();
abstract function chargePrice();
}
class BrickLayers extends Worker{
function removerComponent(){
return ' old blocks removed';
}
function addComponent($what){
return __CLASS__. $this->house->addComponent($what) ;
}
function chargePrice(){
return 'I charged 10,000 ';
}
}
class Painter extends Worker{
function removerComponent(){
return ' remove little part of block where to inset pipe wire';
}
function addComponent($what){
return __CLASS__. $this->house->addComponent($what) ;
}
function chargePrice(){
return 'I charged 6,800 ';
}
}
$layers = new BrickLayers(new House());
echo $layers->addComponent('new block and plaster');
///house is decorated by brick layer
////look at BrickLayers class, does it has access to House class to decorate
///yes, it has extends Worker, so BrickLayers has the same constructor as Worker class
// so inside any method in BrickLayers class, there is access to House class
/// call $this->house whis is defined in Worker
$painter = new Painter(new House());
echo $painter->addComponent('remove old paint and added new azure paint');```
Top comments (0)