9.原型模式

这里写图片描述
原始方法:

index.php

define('BASEDIR',__DIR__);

include BASEDIR . '/IMooc/Loader.php';
spl_autoload_register('\\IMooc\\Loader::autoload');
$canvas1 = new IMooc\Canvas();
$canvas1->init();
//镂空
$canvas1->rect(3,6,4,12);
$canvas1->draw();
echo '<br/>======================================<br/><br/><br/>';
//传统方式,new 两个对象
$canvas2 = new IMooc\Canvas();
$canvas2->init();
//镂空
$canvas2->rect(3,6,4,12);
$canvas2->draw();

原型模式:

Canvas.php

<?php
namespace IMooc;

//模拟一个画布
class Canvas
{
    public $data;
    protected $decorators = array();

    //Decorator
    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;';
            }
        }
    }
}

index.php

<?php

define('BASEDIR',__DIR__);

include BASEDIR . '/IMooc/Loader.php';
spl_autoload_register('\\IMooc\\Loader::autoload');

//新建一个原型方法
$prototype = new IMooc\Canvas();
//只进行了一次 init;
$prototype->init();
//------------

$canvas1 = clone $prototype;
$canvas1->rect(3,6,4,12);
$canvas1->draw();
echo '<br/>======================================<br/><br/><br/>';

$canvas2 = clone $prototype;
$canvas2->rect(5,10,15,20);
$canvas2->draw();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值