<?php
// 抽象组件
interface Component
{
public function operation();
}
// 具体组件
class ConcreteComponent implements Component
{
public function operation()
{
echo “ConcreteComponent operation.\n”;
}
}
// 抽象装饰器
abstract class Decorator implements Component
{
protected $component;
public function __construct(Component $component)
{
$this->component=$component;
}
public function operation()
{
$this->component->operation();
}
}
// 具体装饰器A
class ConcreteDecoratorA extends Decorator
{
public function operation()
{
parent::operation();
$this->addedBehavior();
echo “ConcreteDecoratorA operation.\n”;
}
public function addedBehavior()
{
echo “Added behavior in ConcreteDecoratorA.\n”;
}
}
// 具体装饰器B
class ConcreteDecoratorB extends Decorator
{
public function operation()
{
parent::operation();
$this->addedBehavior();
echo “ConcreteDecoratorB operation.\n”;
}
public function addedBehavior()
{
echo “Added behavior in ConcreteDecoratorB.\n”;
}
}
// 客户端代码
$component=new ConcreteComponent();
$decoratorA=new ConcreteDecoratorA($component);
$decoratorB=new ConcreteDecoratorB($decoratorA);
$decoratorB->operation();
// 抽象组件
interface Component
{
public function operation();
}
// 具体组件
class ConcreteComponent implements Component
{
public function operation()
{
echo “ConcreteComponent operation.\n”;
}
}
// 抽象装饰器
abstract class Decorator implements Component
{
protected $component;
public function __construct(Component $component)
{
$this->component=$component;
}
public function operation()
{
$this->component->operation();
}
}
// 具体装饰器A
class ConcreteDecoratorA extends Decorator
{
public function operation()
{
parent::operation();
$this->addedBehavior();
echo “ConcreteDecoratorA operation.\n”;
}
public function addedBehavior()
{
echo “Added behavior in ConcreteDecoratorA.\n”;
}
}
// 具体装饰器B
class ConcreteDecoratorB extends Decorator
{
public function operation()
{
parent::operation();
$this->addedBehavior();
echo “ConcreteDecoratorB operation.\n”;
}
public function addedBehavior()
{
echo “Added behavior in ConcreteDecoratorB.\n”;
}
}
// 客户端代码
$component=new ConcreteComponent();
$decoratorA=new ConcreteDecoratorA($component);
$decoratorB=new ConcreteDecoratorB($decoratorA);
$decoratorB->operation();
© 版权声明
文章版权归作者所有,未经允许请勿转载。