DEV Community

Azeez Adio
Azeez Adio

Posted on

Decorator Design Pattern in php

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

  1. interface (template for the object to be of the same type)
  2. Class to Decorate that implements the interface
  3. class that decorate(decorator) is and abstract class the implements the interface

Auxiliary components

  1. 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');```





Enter fullscreen mode Exit fullscreen mode

Top comments (0)