首页 > 代码库 > 原型模式
原型模式
定义:先创建好一个原型对象,然后通过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] = ‘ ‘;
}
}
}
}
来自为知笔记(Wiz)
原型模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。