文章摘要
这段代码展示了**装饰器模式**在PHP中的实现,通过定义**抽象组件**和**抽象装饰器**,实现了组件的扩展和复用。具体实现如下:
1. **抽象组件**:定义了`Component`接口,包含一个抽象方法`operation()`,用于执行基本操作。
2. **具体组件**:实现了`ConcreteComponent`类,继承自`Component`,并在`operation()`中输出消息。
3. **抽象装饰器**:定义了`Decorator`类,继承自`Component`,并通过`operation()`方法调用子组件的操作。
4. **具体装饰器**:实现了`ConcreteDecoratorA`和`ConcreteDecoratorB`,它们继承自`Decorator`,并在`operation()`中调用父组件的操作后,添加额外的行为。
5. **客户端代码**:创建了组件实例,并通过装饰器进行扩展,最终调用`operation()`方法。
这段代码通过装饰器模式实现了组件的动态扩展,展示了如何通过继承和操作方法实现功能的逐步增强。
<?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();
© 版权声明
文章版权归作者所有,未经允许请勿转载。