好处:1.原型模式与工厂模式作用类似,都是用来创建对象
2.免去了类创建时重复的初始化操作
3.原型模式适用于大对象的创建。创建一个大对象需要很大的开销,如果每次new就会消耗很大,原型模式仅需内存拷贝即可。
$prototype = new IMoocCanvas();
$prototype->init();
$canvas1 = clone $prototype;
$canvas1->rect(3, 6, 4, 12);
$canvas1->draw();
<?php
namespace IMooc;
class Canvas
{
public $data;
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 draw()
{
foreach ($this->data as $line)
{
foreach ($line as $char)
{
echo $char;
}
echo "<br/> ";
}
}
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] = ' ';
}
}
}
}