一、什么是装饰器模式
装饰器模式:创建装饰者对象,动态添加或修改类的方法,灵活拓展功能
二、装饰器作用
一个类,提供了个方法,如果要对这个方法,修改或添加的功能,传统的编程模式,需要一个子类继承它,并重新实现。 使用装饰器,可以直接在运行时添加一个装饰器对象即可,实现最大的灵活性。
三、实现案例
class MilkTea
{
protected $decorators = array(); // 装饰者数组
public function drink()
{
$this->before();
echo '珍珠';
$this->after();
}
public addDecorator(DrinkDecorator $decorator)
{
$this->decorators[] = $decorator;
}
public function before()
{
foreach($this->decorators as $decorators) {
$decorators->beforeDrink();
}
}
public function after()
{
foreach($this->decorators as $decorators) {
$decorators->aftereDrink();
}
}
}
// 装饰器接口
interface DrinkDecorator
{
public function beforeDrink();
public function afterDrink();
}
// 装饰者1 【温度】
class Temperature implements DrinkDecorator
{
protected $temperature;
public function __construct($temperature = '去冰')
{
$this->temperature = $temperature;
}
public function beforeDrink()
{
echo $this->temperature;
}
public function afterDrink()
{
echo '';
}
}
// 调用
$milkTea = new MilkTea();
// 对类的方法进行拓展, 调用装饰者1
$milkTea->addDecorator(new Temperature('常温'));
// 装饰者2 【甜度】
$milkTea->drink();