PHP 设计模式 装饰器(者)模式

    技术2023-10-11  101

    装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装例1: <?php class Food{ public $fruit; function addFruit($fruit){ $this->fruit = $fruit; } function eat(){ echo '吃'.$this->fruit; } } class FoodDecorate{ public function makeDecorate($food){ $food->fruit ='削皮的苹果'; } } $obj = new Food(); $obj->addFruit('苹果');//吃苹果 $dec = new FoodDecorate(); $dec->makeDecorate($obj); $obj->eat();//吃削皮的苹果 例2: <?php class Food { public $fruit; function addFruit($fruit) { $this->fruit = $fruit; } function eat() { echo '吃' . $this->fruit; } } class FoodDecorate { public $fruit; public function __construct(Food $fruit) { $this->fruit = $fruit; } public function eat(){ echo '吃青'.$this->fruit->fruit; } } $obj = new Food(); $obj->addFruit('苹果');//吃苹果 $tt = new FoodDecorate($obj); $tt->eat();//吃青苹果
    Processed: 0.027, SQL: 9