<?php /** * 原型模式 * * 允许一个对象再创建另外一个可定制的对象, * 根本无需知道任何如何创建的细节, * 工作原理是:通过将一个原型对象传给那个要发动创建的对象, * 这个要发动创建的对象通过请求原型对象拷贝它们自己来实施创建 * * @author doodoo<[email protected]> * */ class Prototype{ private $id = null,$name = null; public function __construct(){ $this->id = "0"; $this->name = "panwei"; } public function copy(Prototype $p){ $q = new Prototype(); $q->id = $p->id + 1; $q->name = "doodoo"; return $q; } } $prototype = new Prototype(); $p2 = $prototype->copy($prototype); print_r($prototype); print_r($p2); ?> 其实PHP5内置有clone函数,这样的话我们的实现一下边的简单起来,以上代码可以修改成这样 <?php /** * 原型模式 * * 允许一个对象再创建另外一个可定制的对象, * 根本无需知道任何如何创建的细节, * 工作原理是:通过将一个原型对象传给那个要发动创建的对象, * 这个要发动创建的对象通过请求原型对象拷贝它们自己来实施创建 * * @author doodoo<[email protected]> * */ class Prototype{ private $id = null,$name = null; public function __construct(){ $this->id = "0"; $this->name = "panwei"; } /** * 对象被clone的时候该方法将被调用 */ public function __clone(){ $this->id ++; $this->name = "doodoo"; return $q; } } $prototype = new Prototype(); $p2 = clone $prototype; print_r($prototype); print_r($p2); ?> 在PHP5中对原型模式的使用变成了对clone函数的使用及__clone()函数的实现。 
|