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());
场景事例:
咖啡 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());
相关文章推荐
- PHP设计模式-装饰器模式
- PHP设计模式——装饰器模式
- PHP设计模式-装饰器模式
- php设计模式之———装饰器模式
- PHP设计模式——装饰器模式
- PHP设计模式——装饰器模式(decorator)
- 介绍php设计模式中的工厂模式
- 一种PHP设计模式:DPT
- 五种常见的PHP设计模式(择自互联网非本人所写)
- 五种常见的PHP设计模式
- 另外五个 PHP 设计模式
- [介绍]PHP设计模式:DAO(数据访问对象模式)
- 一种PHP设计模式:DPT
- 架构师常用的五种 PHP 设计模式
- php设计模式介绍之编程惯用法第1/3页
- php设计模式介绍之值对象模式第1/5页
- [转]五种常见的PHP设计模式
- 五种常见的PHP设计模式
- [介绍]PHP设计模式:DAO(数据访问对象模式)
- php设计模式-中级