说明
将一个对象作为原型,对其进行复制、克隆,产生一个和原对象类似的新对象。
示例
下面看下原型模式的代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| abstract class Prototype{ public $v = 'clone'.PHP_EOL; public function __construct(){ echo 'create'.PHP_EOL; } abstract public function __clone(); }
class ConcretePrototype1 extends Prototype{ public function __clone(){
} public function init($param){ $this->v = $param; } }
class ConcretePrototype2 extends Prototype{ public function __clone(){ $this->v = 'clone 2'; } }
$p = new ConcretePrototype1(); $p->init('hello'); $p1 = clone $p; echo $p->v.'=='.$p1->v;
$p = new ConcretePrototype2(); $p2 = clone $p; echo $p->v.'=='.$p2->v;
|
总结
特点:减少创建对象时的开销