时间:2021-07-01 10:21:17 帮助过:5人阅读
<?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;
装饰模式降低了系统的耦合度,可以动态增加或删除对象的职责,并使得需要装饰的具体构件类和具体装饰类可以独立变化,以便增加新的具体构件类和具体装饰类
相关推荐:
详解PHP装饰模式的示例代码
php装饰模式
易懂的PHP设计模式之单例模式
以上就是PHP设计模式之装饰器模式详解的详细内容,更多请关注Gxl网其它相关文章!