PHP装饰者模式

来源:互联网 发布:windows 查询端口 编辑:程序博客网 时间:2024/06/18 10:26

装饰者模式

interface Beverage{public function cost();}//被装饰class Coffee implements Beverage{public function cost(){return 1;} }//装饰者class CondimentDecorator implements Beverage{public function cost(){}}class Milk extends CondimentDecorator{private $_beverage;public function __construct($beverage){if($beverage instanceof Beverage) {$this->_beverage = $beverage;}}public function cost(){return $this->_beverage->cost() + 2;}}class Sugar extends CondimentDecorator{private $_beverage;public function __construct($beverage){if($beverage instanceof Beverage){$this->_beverage = $beverage;}}public function cost(){return $this->_beverage->cost()+3;}}$coffee = new Coffee();//加牛奶$coffee = new Milk($coffee);//加糖$coffee = new Sugar($coffee);//总消费echo $coffee->cost();


0 0