您的位置:首页 > 其它

9.原型模式

2016-03-05 23:24 295 查看


原始方法:

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] = ' ';
}
}
}
}


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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: