定义:装饰器模式可以动态的添加修改类的功能
初始的一个类,无任何修饰,只简单的输出helloworld
<?
class HelloWorld {
protected $output="HelloWorld";
public function output()
{
echo $this->output;
}
}
$hw=new HelloWorld();
$hw->output();
现在运用装饰期模式来给来给该类的输出增加颜色,代码如下
<?php
/**
*
* @authors mtg
* @date 2015-08-31 09:45:01
*/
/*此处的作用是
*定义一个装饰器接口
*/
interface Decorator{
function before_method();
function after_method();
}
/*此处的作用是
*定义一个颜色装饰器
*/
class ColorDecorator implements Decorator{
protected $color;
function __construct($value='')
{
$this->color=$value;
}
public function before_method()
{
echo "<div style='color:".$this->color."'>";
}
public function after_method()
{
echo "</div>";
}
}
class HelloWorld {
protected $decorator=array();
protected $output="HelloWorld";
public function addDecorator(Decorator $decorator)
{
$this->decorator[]=$decorator;
}
public function output()
{
$this->before_op();
echo $this->output;
$this->after_op();
}
public function before_op(){
if (!empty($this->decorator)) {
foreach ($this->decorator as $key => $value) {
$value->before_method();
}
}
}
public function after_op()
{
/*此处的作用是
*需要将装饰器倒序后再调用方法
*/
if (!empty($this->decorator)) {
$this->decorator=array_reverse($this->decorator);
foreach ($this->decorator as $key => $value) {
$value->after_method();
}
}
}
}
$hw=new HelloWorld();
$hw->output();
$colordecorator=new ColorDecorator('red');
$hw->addDecorator($colordecorator);
$hw->output();