装饰器模式是一个常见的设计模式,经典使用场景是商品销售。
下面就是一个典型的装饰器模式,用PHP语言描述。
/**
* Interface IComponent 组件对象接口
* Author wonjia
*/
interface IComponent {
public function getName();
public function getPrice();
}
/**
* Class Car 待装饰对象
*/
class Car implements IComponent {
private $_name;
private $_price;
/**
* Person constructor. 构造方法
*
* @param $name 汽车的名称和价格
*/
public function __construct($name, $price) {
$this->_name = $name;
$this->_price = $price;
}
public function getName() {
return $this->_name;
}
public function getPrice() {
return $this->_price;
}
}
/**
* Class Extra 所有装饰器父类 额外产品
*/
class Extra implements IComponent {
protected $component;
/**
* 接收装饰对象
*
* @param IComponent $component
*/
public function decorate(IComponent $component) {
$this->component = $component;
}
public function getName() {
if(!empty($this->component)) {
return $this->component->getName();
}
}
public function getPrice() {
if(!empty($this->component)) {
return $this->component->getPrice();
}
}
}
/* 下面为具体装饰器类 */
/**
* Class baoXian 保险
*/
class baoXian extends Extra{
public function getName() {
return parent::getName() . " 保险 ";
}
public function getPrice() {
return parent::getPrice() * 1.1;
}
}
/**
* Class jiaoDian 脚垫
*/
class jiaoDian extends Extra {
public function getName() {
return parent::getName() . " 脚垫 ";
}
public function getPrice() {
return parent::getPrice() + 500;
}
}
/**
* Class jingHuaQi 净化器
*/
class jingHuaQi extends Extra {
public function getName() {
return parent::getName() . " 净化器 ";
}
public function getPrice() {
return parent::getPrice() + 1200;
}
}
/**
* Class mieHuoQi 灭火器
*/
class mieHuoQi extends Extra {
public function getName() {
return parent::getName() . " 灭火器 ";
}
public function getPrice() {
return parent::getPrice() + 200;
}
}
/**
* Class Client
*/
class Client {
public static function order() {
//昂科威
$car1 = new Car('昂科威', 230000);
$baoXian = new baoXian();
$jiaoDian = new jiaoDian();
$baoXian->decorate($car1);
$jiaoDian->decorate($baoXian);
echo $jiaoDian->getName();
echo $jiaoDian->getPrice() . '元';
echo '<br />';
//GL8
$car2 = new Car('GL8', 310000);
$jingHuaQi = new jingHuaQi();
$mieHuoQi = new mieHuoQi();
$jingHuaQi->decorate($car2);
$mieHuoQi->decorate($jingHuaQi);
echo $mieHuoQi->getName();
echo $mieHuoQi->getPrice() . '元';
echo '<br />';
}
}
Client::order();