原型模式有什么用?

原型模式(Prototype) Prototype原型模式是一种创建型设计模式,Prototype模式允许一个对象再创建另外一个可定制的对象,根本无需知道任何如何创建的细节,工作原理是:通过将一个原型对象传给那个要发动创建的对象,这个要发动创建的对象通过请求原型对象拷贝它们自己来实施创建。 解决什么问题 它主要面对的问题是:“某些结构复杂的对象”的创建工作;由于需求的变化,这些对象经常面临着剧烈的变化,但是他们却拥有比较稳定一致的接口。 使用php提供的clone()方法来实现对象的克隆,所以Prototype模式实现一下子变得很简单。并可以使用php的__clone() 函数完成深度克隆。 代码实例
<?php

//定义原型类接口

interface prototype{

public function copy();

}

//一个具体的业务类并实现了prototype 接口

//以一个文本的读写操作类为例

class text implements prototype{

private $_fileUrl;

public function __construct($fileUrl){

$this->_fileUrl = $fileUrl;

}

public function write($content){

file_put_contents($this->_fileUrl, $content);

}

public function read(){

return file_get_contents($this->_fileUrl);

}

public function copy(){

return clone $this;

}

/* 可以使用php的__clone() 函数完成深度克隆 */

public function __clone(){

echo 'clone...';

}

}

$texter1 = new text('1.txt');

$texter1->write('test...');

//获得一个原型

$texter2 = $texter1->copy();

echo $texter2->read();

 

posted @ 2022-05-17 01:19  穷帅哥依然纵横一方  阅读(158)  评论(0编辑  收藏  举报