您的位置:首页 > 编程语言 > PHP开发

PHP装饰者模式

2016-04-28 14:59 543 查看
装饰者模式

interface Beverage
{
public function cost();
}

//被装饰
class Coffee implements Beverage
{
public function cost()
{
return 1;
}
}

//装饰者
class CondimentDecorator implements Beverage
{
public function cost()
{

}
}

class Milk extends CondimentDecorator
{
private $_beverage;
public function __construct($beverage)
{
if($beverage instanceof Beverage) {
$this->_beverage = $beverage;
}
}

public function cost()
{
return $this->_beverage->cost() + 2;
}
}

class Sugar extends CondimentDecorator
{
private $_beverage;

public function __construct($beverage)
{
if($beverage instanceof Beverage)
{
$this->_beverage = $beverage;
}
}

public function cost()
{
return $this->_beverage->cost()+3;
}
}

$coffee = new Coffee();
//加牛奶
$coffee = new Milk($coffee);
//加糖
$coffee = new Sugar($coffee);

//总消费
echo $coffee->cost();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: