原型模式

定义:先创建好一个原型对象,然后通过clone原型对象来创建新的对象。
好处:1.原型模式与工厂模式作用类似,都是用来创建对象
          2.免去了类创建时重复的初始化操作  
          3.原型模式适用于大对象的创建。创建一个大对象需要很大的开销,如果每次new就会消耗很大,原型模式仅需内存拷贝即可。

$prototype = new \IMooc\Canvas();
$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/>\n";
}
}

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


来自为知笔记(Wiz)


posted on 2016-12-24 22:13  果然朝辉  阅读(143)  评论(0编辑  收藏  举报

导航