装饰器模式可以动态的添加修改类的功能,.个类提供了一项功能,如果要在修改并添加额外的功能,传统的编程是写一个子类去继承它,并重新实现类的方法,使用装饰器模式,仅需在运行时添加一个装饰器对象即可实现,可以实现最大的灵活性
<?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设计模式之装饰器模式详解的详细内容。