php 设计模式(装饰器模式和原型模式组合)

<?php
/**
 * 1.装饰器模式可以动态地 添加修改类的功能
 * 2.1个类完成一个功能如果要修改添加额外的功能,传统的编程模式需要写一个子类继承他,并重新实现类的方法
 * 3.使用装饰器模式,仅需在运行时添加-个装饰器对象即可实现,可以实现最大的灵活性
 */
interface DrawDecorator{
    public function afterDraw();
    public function beforeDraw();
}
class Dec implements DrawDecorator{
    public function __construct($color = 'red'){
        $this->color = $color;
    }
    public function afterDraw()
    {
        echo '</div>';
    }
    public function beforeDraw()
    {
      echo "<div style = 'color:{$this->color};'>";
    }
}
class Dec2 implements DrawDecorator{
    public function __construct($size = '20'){
        $this->size = $size;
    }
    public function afterDraw()
    {
        echo '</div>';
    }
    public function beforeDraw()
    {
        echo "<div style = 'font-size:{$this->size};'>";
    }
}

class Canvas
{
    public $data;
    protected $decorators = array();

    //初始化画布
    function init($width = 20, $height = 10)
    {
        $data = array();
        for($i = 0; $i < $height; $i++)
        {
            for($j = 0; $j < $width; $j++)
            {
                $data[$i][$j] = '*';
            }
        }
        $this->data = $data;
    }

    function addDecorator(DrawDecorator $decorator)
    {
        $this->decorators[] = $decorator;
    }

    function beforeDraw()
    {
        foreach($this->decorators as $decorator)
        {
            $decorator->beforeDraw();
        }
    }

    function afterDraw()
    {
        $decorators = array_reverse($this->decorators);
        foreach($decorators as $decorator)
        {
            $decorator->afterDraw();
        }
    }

    function draw()
    {
        $this->beforeDraw();
        foreach($this->data as $line)
        {
            foreach($line as $char)
            {
                echo $char;
            }
            echo "<br />\n";
        }
        $this->afterDraw();
    }

    function rect($a1, $a2, $b1, $b2)
    {
        foreach($this->data as $k1 => $line)
        {
            if ($k1 < $a1 or $k1 > $a2) continue;
            foreach($line as $k2 => $char)
            {
                if ($k2 < $b1 or $k2 > $b2) continue;
                $this->data[$k1][$k2] = '&nbsp;';
            }
        }
    }
}
$prototype = new Canvas();
$prototype->init();
$prototype->addDecorator(new Dec());

//原型模式
$ca1 = clone $prototype;
$ca1->rect(3, 6, 4, 12);
$ca1->draw();
echo '<br/>';
$prototype->addDecorator(new Dec2());
$ca2= clone $prototype;
$ca2->rect(1, 3, 2, 6);
$ca2->draw();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值