Decorator(装饰器)模式能够像标准的继承一样为类添加新的功能。

不同于标准继承机制的是,如果对象进行了实例化,Decorator模式能够在运行时动态地为对象添加新的功能。

<?php
abstract class AbstractCar{
    public abstract  function getPrice();
    public abstract function getManufacturer();
}
class Car extends AbstractCar{
    private  $price=200000;
    private $manufacturer='bmw';
    public function getPrice(){
        return $this->price;
    }
    public function getManufacturer(){
        return $this->manufacturer;
    }
}

class CarDecorator extends AbstractCar{
    private $target;
    public function __construct(Car $target){
        $this->target=$target;
    }
    public function getPrice(){
        return $this->target->getPrice();
    }
    public function getManufacturer(){
        return $this->target->getManufacturer();
    }
}

class NavigationSystem extends CarDecorator{
    public function getPrice(){
        return parent::getPrice()+1000;
    }
}

$car=new Car();
$car=new NavigationSystem($car);

echo $car->getPrice();

?>

 

相关文章:

  • 2021-10-24
  • 2021-08-11
  • 2021-04-04
猜你喜欢
  • 2021-12-18
  • 2021-08-18
  • 2021-06-08
  • 2022-12-23
  • 2021-12-12
  • 2021-06-22
相关资源
相似解决方案