Prototype pattern (Prototype)
Prototype prototype pattern is a creative design pattern. Prototype pattern allows one object to create another customizable object. , without knowing any details of how to create it, works like this: by passing a prototype object to the object to be created, the object to be created is created by requesting the prototype object to copy itself.
What problem is solved
The main problem it faces is: the creation of "some objects with complex structures"; due to changes in requirements, these objects often face are undergoing drastic changes, but they have relatively stable and consistent interfaces.
Use the clone() method provided by PHP to clone objects, so the implementation of Prototype mode suddenly becomes very simple. And you can use PHP's __clone() function to complete deep cloning.
Code Example
<?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();
The above is the detailed content of What is the use of prototype mode?. For more information, please follow other related articles on the PHP Chinese website!