PHP设计模式笔记八:原型模式 -- Rango韩老师 http://www.imooc.com/learn/236

时间:2023-03-09 05:36:17
PHP设计模式笔记八:原型模式 -- Rango韩老师 http://www.imooc.com/learn/236

原型模式

  概述:

  1、与工厂模式作用类似,都是用来创建对象

  2、与工厂模式的实现不同,原型模式是先创建好一个原型对象,然后通过clone原型对象来创建新的对象,这样就免去了类创建时重复的初始化操作

  3、原型模式适用于大对象的创建,创建一个大对象需要很大的开销,如果每次new就会消耗很大,原型模式仅需内存拷贝即可

  代码如下:

  1、编写一个画图类: 

 <?php
namespace IMooc; class Canvas{ public $data;
/**
* [生成一块宽为20,高为10的包含*的画布]
* @param integer $width [画布宽]
* @param integer $height [画布高]
* @return [type] [description]
*/
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;
}
/**
* [画画,也就是使用-替换*]
* @param [type] $a1 [最小高度]
* @param [type] $a2 [最大高度]
* @param [type] $b1 [最小宽度]
* @param [type] $b2 [最大宽度]
* @return [type] [description]
*/
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] = '-';
}
}
} /**
* [输出到浏览器]
* @return [type] [description]
*/
function draw(){ foreach($this->data as $line){
foreach($line as $char){
echo $char;
}
echo "<br>";
}
} }

  在入口文件index.php实例化Canvas对象,进行绘图  

 <?php

 define('BASE_PATH',__DIR__);
// echo BASE_PATH;
require './IMooc/Framework.php';
spl_autoload_register('\IMooc\Framework::autoload'); $canvas1 = new IMooc\Canvas();
$canvas1->init(); $canvas2 = new IMooc\Canvas();
$canvas2->init(); $canvas1->rect(3,6,4,12);
$canvas1->draw(); $canvas2->rect(2,6,4,8);
//$canvas2->draw();
output输出结果
********************
********************
********************
****---------*******
****---------*******
****---------*******
****---------*******
********************
********************
******************** 

 创建两个Canvas对象,如果Canvas初始化工作很多,很复杂,实例化对象对资源消耗就比较严重,这时可以考虑使用原型模式进行优化

<?php

define('BASE_PATH',__DIR__);
// echo BASE_PATH;
require './IMooc/Framework.php';
spl_autoload_register('\IMooc\Framework::autoload'); $prototype = new IMooc\Canvas();
$prototype->init(); //使用clone避免每次直接进行初始化操作
$canvas1 = clone $prototype;
$canvas1->rect(3,6,4,12);
$canvas1->draw(); $canvas2 = clone $prototype;
$canvas2->rect(3,6,4,12);
$canvas2->draw();