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

php设计模式——装饰器模式

2015-01-15 19:51 411 查看
装饰器模式,对已有对象的部分内容或者功能进行调整,但是不需要修改原始对象结构,可以使用装饰器

场景事例:

咖啡 1 元一杯,加点牛奶0.2元,加点糖0.2元,在不修改咖啡类的情况下,使用装饰器模式

<?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 Milk extends Coffee{
public $_beverage;
public function __construct($beverage){
$this->_name = 'Milk';
$this->_beverage = $beverage;
}
public function Cost(){
return $this->_beverage->Cost() + 0.2;
}
}
class Sugar extends Coffee{
public $_beverage;
public function __construct($beverage){
$this->_name = 'Sugar';
$this->_beverage = $beverage;
}
public function Cost(){
return $this->_beverage->Cost() + 0.2;
}
}

// Test Case
//1.拿杯咖啡
$coffee = new Coffee();
//2.加点牛奶
$coffee = new Milk($coffee); //此时的$coffee已经是milk的对象了
//3.加点糖
$coffee = new Sugar($coffee); //此时的$coffee是糖的对象

printf("Coffee Total:%0.2f\n",$coffee->Cost());
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: