PHP 常见设计模式及示例
<?php
// 装饰器模式示例
interface Component {
public function operation();
}
class ConcreteComponent implements Component {
public function operation() {
echo "具体对象的操作方法。\n";
}
}
abstract class Decorator implements Component {
protected $component;
public function __construct(Component $component) {
$this->component = $component;
}
}
class ConcreteDecoratorA extends Decorator {
public function operation() {
$this->component->operation();
$this->addedState = "新增状态A";
$this->addedBehavior();
}
private $addedState;
private function addedBehavior() {
echo "具体装饰类A的操作方法。\n";
}
}
class ConcreteDecoratorB extends Decorator {
public function operation() {
$this->component->operation();
$this->addedState = "新增状态B";
$this->addedBehavior();
}
private $addedState;
private function addedBehavior() {
echo "具体装饰类B的操作方法。\n";
}
}
// 使用示例
$component = new ConcreteComponent();
$decoratorA = new ConcreteDecoratorA($component);
$decoratorB = new ConcreteDecoratorB($decoratorA);
$decoratorB->operation(); // 输出装饰后的操作结果
?>
这个示例代码展示了如何在PHP中实现装饰器模式。首先定义了一个Component接口和一个ConcreteComponent类,这是被装饰的基础组件。然后定义了一个抽象的Decorator类,用于保存对Component的引用。接着定义了两个具体的装饰类ConcreteDecoratorA和ConcreteDecoratorB,它们在基础操作的基础上添加了额外的状态和行为。最后,我们创建了一个ConcreteComponent对象,并给它加上了装饰,并调用了最终装饰后的operation方法。
评论已关闭