php-设计模式-装饰模式

装饰模式(Decorator)动态的给一个对象添加一些额外的职责,就增加功能来讲,装饰模式比子类更加灵活[DP]


标准UML图


PHP-版本UML图



<?php

#饮料类 也可以是一个抽象类-
interface drinks
{
function desc();
}

# 具体饮料类 咖啡
class coffee implements drinks
{
public function desc()
{
echo '我是咖啡';
}
}

#饮料混合类
abstract class drinkMix implements drinks
{
public function desc()
{
//
}
}

#饮料类
class milk extends drinkMix
{
protected $state;

public function __construct(drinks $drinks)
{
if($drinks instanceof drinks){
$this->state = $drinks;
}else{
die('error');
}

}

public function desc()
{
echo $this->state->desc(),'加牛奶';
}

}

#饮料类
class tea extends drinkMix
{
public $state;

public function __construct(drinks $drinks)
{
if($drinks instanceof drinks){
$this->state = $drinks;
}else{
die('error');
}

}

public function desc()
{
echo $this->state->desc(),'加茶水';
}

}


$coffee = new coffee();

$coffee = new milk($coffee);
$coffee = new tea($coffee);

$coffee->desc();


总结: 看懂UML是理解的关键

tags: PHP,设计模式