前言:
原型模式:利用clone方法,复制出新的对象。
看到这里,你肯定会有疑问,这不是和工厂模式很类似的吗?也是不停的生产出新的对象.
那么它究竟和工厂模式有什么具体的区别呢?
下面就是答案:
(转)使用原型模式创建对象比直接new一个对象在性能上要好的多,因为Object类的clone方法是一个本地方法,它直接操作内存中的二进制流,特别是复制大对象时,性能的差别非常明显。
<?php /**定义一个Prototype原型的接口 * Interface Prototype */ interface Prototype{ public function copy(); } /** * 子类去继承Prototype原型接口,并且实现copy方法 * Class Student */ class Student implements Prototype{ public $name; public $age; public $sex; public function __construct($name,$age,$sex){ $this->name = $name; $this->age = $age; $this->sex = $sex; } public function getStudentInformation(){ echo "student name is ".$this->name." student age is".$this->age." student sex is".$this->sex; } public function copy(){ return clone $this; } } $student1=new Student("dennis","26","man"); //$student1->getStudentInformation(); $student2=$student1->copy(); $student2->name = "Jack"; $student2->getStudentInformation();