原型模式
操作: 先创建好一个原型对象,然后通过clone 原型对象来创建新的对象。这就免去了类创建时重复的初始化操作。
原型模式适用于大对象的创建。如果每次new 就会消耗很大,原型模式仅需要内存拷贝即可。
index.php 中
$prototype = new Imooc\Canvas();
$prototype->init(); //需要做很多很复杂的,耗时的处理
$prototype->rect(3, 6, 4, 12);
$prototype->draw();
echo "==================<br/>\n";
$canvas2 = clone $prototype;
$canvas2->rect(1,3, 2, 6); //和直接new 相比省掉 了init
$canvas2->draw();
Canvas.php 中
<?php
/**
* Created by PhpStorm.
*/
namespace Imooc;
class Canvas
{
public $data;
//protected $decorators = array();
public 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;
}
public 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] = ' ';
}
}
}
/*
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();
}
}
*/
public function draw()
{
//$this->beforeDraw();
foreach ($this->data as $line)
{
foreach ($line as $char)
{
echo $char;
}
echo "<br/>\n";
}
//$this->afterDraw();
}
}