<?php /** * 装饰者模式 * 动态的为对象增加职责 */ interface Drink { public function cost(); } class Coffee implements Drink { public function cost() { return 10; } } abstract class Drink_Decorator implements Drink { protected $drink; public function __construct($drink) { $this->drink = $drink; } } class Sugar extends Drink_Decorator { public function cost() { return $this->drink->cost() + 6; } } class Milk extends Drink_Decorator { public function cost() { return $this->drink->cost() + 7; } } $coffee = new Coffee(); $coffee = new Sugar($coffee); $coffee = new Milk($coffee); echo $coffee->cost();
这个例子,估计看过设计模式的人都太熟悉了
来个项目案例
待续