Decorator model can dynamically add and modify the function of a class. Each class provides a function. If you want to modify and add additional functions, traditional programming It is to write a subclass to inherit it and reimplement the class method, using the decorator pattern, and only need to add a decorator## at runtime. #Object can be implemented to achieve maximum flexibility
<?php /* * 装饰模式 */ abstract class Beverage { public $_name; abstract public function Cost(); } // 被装饰者类 class Coffee extends Beverage { public function construct() { $this->_name = 'Coffee'; } public function Cost() { return 1.00; } } // 以下三个类是装饰者相关类 class CondimentDecorator extends Beverage //装饰类 { public function construct() { $this->_name = 'Condiment'; } public function Cost() { return 0.1; } } class Milk extends CondimentDecorator //牛奶 配料 --装饰者 { public $_beverage; public function construct($beverage) { if ($beverage instanceof Beverage) { $this->_beverage = $beverage; } else exit('Failure'); } public function Cost() { return $this->_beverage->Cost() + 0.2; } } class Sugar extends CondimentDecorator //糖 配料 --装饰者 { public $_beverage; public function construct($beverage) { $this->_name = 'Sugar'; if ($beverage instanceof Beverage) { $this->_beverage = $beverage; } else { exit('Failure'); } } public function Cost() { return $this->_beverage->Cost() + 0.2; } } // Test Case //1.拿杯咖啡 $coffee = new Coffee(); //2.加点牛奶 $coffee = new Milk($coffee); //3.加点糖 $coffee = new Sugar($coffee); echo $coffee->Cost(); echo $coffee->_name;
Related recommendations:
Detailed sample code for PHP decoration mode
Easy to understand PHP Design pattern singleton pattern
The above is the detailed content of Detailed explanation of the decorator pattern of PHP design patterns. For more information, please follow other related articles on the PHP Chinese website!