Decorator模式

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();

?>

 

posted @ 2015-03-22 20:53  H&K  阅读(292)  评论(0编辑  收藏  举报