装饰器模式

定义:装饰器模式可以动态的添加修改类的功能

初始的一个类,无任何修饰,只简单的输出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();


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值