装饰模式:动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
abstract class Component
{
public abstract function Operation();
}
class ConcreteComponent extends Component
{
public function Operation()
{
echo '具体对象的操作<br>';
}
}
abstract class Decorator extends Component
{
protected $component;
public function setComponent($component){
$this->component = $component;
}
public function Operation()
{
if($this->component != null){
$this->component->Operation();
}
}
}
class ConcreteDecoratorA extends Decorator
{
private $addedState;
public function Operation()
{
parent::Operation(); // TODO: Change the autogenerated stub
$this->addedState = "New State";
echo "具体装饰对象A的操作<br>";
}
}
class ConcreteDecoratorB extends Decorator
{
public function Operation()
{
parent::Operation(); // TODO: Change the autogenerated stub
$this->addedBehavior();
echo "具体装饰对象B的操作<br>";
}
private function addedBehavior(){
}
}
$c = new ConcreteComponent();
$d1 = new ConcreteDecoratorA();
$d2 = new ConcreteDecoratorB();
$d1->setComponent($c);
$d2->setComponent($d1);
$d2->Operation();
Component是定义一个对象接口,可以给这些对象动态地添加职责,ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责。Decorator,装饰抽象类,继承了Component,从外类来扩展Component类的功能
但对于Component来说,是无需知道Decorator的存在的。对于ConcreteDecorator就是具体的装饰对象,起到给Component添加职责的功能
装饰模式是利用setComponent来对对象进行包装的,这样每个装饰对象的实现就和如何使用这个对象分离了,每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链当中
如果只有一个ConcreteComponent类而没有抽象的Component类,那么Decorator类可以是ConcreteComponent的一个子类。如果只有一个ConcreteDecorator类,那么就没有必要建立一个单独的Decorator类,可以把Decorator和ConcreteDecorator的责任合并成一个类.
#相当于ConcreteComponent
class Person
{
private $name;
public function __construct($name)
{
$this->name = $name;
}
public function Show(){
echo '装扮的'.$this->name.'<br>';
}
}
//Decorator
class Finery extends Person
{
public function __construct()
{
parent::__construct('');
}
private $component;
public function setComponent($component){
$this->component = $component;
}
public function Show()
{
if ($this->component != null){
$this->component->Show();
}
}
}
class TShirts extends Finery
{
public function Show()
{
echo '大T恤<br>';
parent::Show(); // TODO: Change the autogenerated stub
}
}
class Sneakers extends Finery
{
public function Show()
{
echo '拖鞋<br>';
parent::Show(); // TODO: Change the autogenerated stub
}
}
class BigTrouser extends Finery
{
public function Show()
{
echo '垮裤<br>';
parent::Show(); // TODO: Change the autogenerated stub
}
}
$paul = new Person('paulversion');
echo '第一种装扮<br>';
$sneaker = new Sneakers();
$trouser = new BigTrouser();
$shirts = new TShirts();
$sneaker->setComponent($paul);
$trouser->setComponent($sneaker);
$shirts->setComponent($trouser);
$shirts->Show();
装饰模式是为已有功能动态地添加更多功能的一种方式.装饰模式把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择地,按顺序地使用装饰功能包装对象.