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{
private $_beverage;
public function __construct($beverage){
$this -> _name = 'Milk';
$this -> _beverage = $beverage;
}
public function Cost(){
return $this -> _beverage -> Cost() + 0.2;
}
}
class Sugar extends CondimentDecorator{
private $_beverage;
public function __construct($beverage){
$this -> _name = 'Sugar';
$this -> _beverage = $beverage;
}
public function Cost(){
return $this -> _beverage -> Cost() + 0.3;
}
}
$coffee = new Sugar(new Milk(new Coffee()));
echo $coffee -> Cost();
Javascript:
var Coffee = function(){
this.name = 'Coffee';
this.Cost = function(){
return 1.0;
}
}
var Milk = function(beverage){
this.name = 'Milk';
this.Cost = function(){
return beverage.Cost() + 0.2;
}
}
var Sugar = function(beverage){
this.name = 'Sugar';
this.Cost = function(){
return beverage.Cost() + 0.3;
}
}
var beverage = new Sugar(new Milk(new Coffee()));
console.log(beverage.Cost());
总结:保持原有的接口,并为原来的动态的添加新的功能。增加一个修饰类包裹原来的类,包裹的方式一般是通过在将原来的对象作为修饰类的构造函数的参数。采用了组合对象的方式。