装饰器模式
装饰器模式就是对一个已有的结构增加装饰。装饰模式是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。 基本说来, 如果想为现有对象增加新功能而不想影响其他对象, 就可以使用装饰器模式.
Demo:
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){
$this->_name = 'Milk';
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);
printf("Coffee Total:%0.2f元\n",$coffee->Cost());