一、什么是原型模式
原型模式简单理解:先创建好一个原型对象,然后通过clone原型对象,来创建新的对象。
二、使用原型模式的好处
原型模式适用于大对象的创建,比如一个对象创建的时候需要初始化很多东西,产生大的开销,这时候用原型模式,就可以避免类创建时重复初始化的开销。
三、具体实现
1、比如有以下A对象:
class A
{
public $color;
public $height;
public $width;
// 开销比较大的初始化
public function init(string $color = 'green', int $height = 100, int $width = 100)
{
$this->color = $color;
$this->height = $height;
$this->width = $width;
// long long code ...
}
public function height()
{
return $this->height;
}
}
2、未使用原型模式调用
$test1 = new A();
$test1->init();
$height1 = $test1->height();
$test2 = new A();
$test2->init();
$height2 = $test2->height();
3、使用原型对象模式调用
$prototype = new A(); // 创建原型对象
$prototype->init();
$test1 = clone $prototype; // 克隆原型对象
$height1 = $test1->height();
$test2 = clone $prototype;
$height2 = $test2->height();