简单的用php实现了装饰器模式:
<?php
/**
*简单的装饰器模式
*/
class PrintText
{
protected $decorators = [];
public function print()
{
$this->before();
echo "hello world" . PHP_EOL;
$this->after();
}
public function addDecorators(Decorator $decorator)
{
$this->decorators[] = $decorator;
}
protected function before()
{
foreach ($this->decorators as $key => $value) {
$value->before();
}
}
//使用栈的方式,先进后出
protected function after()
{
$decorators = array_reverse($this->decorators);
foreach($decorators as $key => $value){
$value->after();
}
}
}
interface Decorator
{
public function before();
public function after();
}
class Font implements Decorator
{
public function before()
{
echo "fonts before" . PHP_EOL;
}
public function after()
{
echo "fonts after" . PHP_EOL;
}
}
class Color implements Decorator
{
public function before()
{
echo "color before" . PHP_EOL;
}
public function after()
{
echo "color after" . PHP_EOL;
}
}
$print = new PrintText();
$print->addDecorators(new Font());
$print->addDecorators(new Color());
$print->print();
//output results
/**
fonts before
color before
hello world
color after
fonts after
*/
代码比较简单,如果有什么问题,还请不吝赐教。