原型模式:
用原型实例指定创建对象的种类,并且通过拷贝这个原型来创建新的对象。
应用场景: 类的资源非常多、性能和安全要求,一般和工厂方法结合使用。
<br /><?php<br />/**<br /> * 原型模式<br /> */<br />//声明一个克隆自身的接口<br />interface Prototype {<br /> function copy(); <br />} <br />//产品要实现克隆自身的操作<br />class Student implements Prototype {<br /> //简单起见,这里没有使用get set<br /> public $school;<br /> public $major;<br /> public $name;<br /> public function __construct($school, $major, $name) {<br /> $this->school = $school;<br /> $this->major = $major;<br /> $this->name = $name;<br /> }<br /> public function printInfo() {<br /> printf("%s,%s,%sn", $this->sch<a style="color:transparent">本@文来源gao($daima.com搞@代@#码(网5</a><strong>搞gaodaima代码</strong>ool, $this->major, $this->name);<br /> }<br /> public function copy() {<br /> return clone $this;<br /> }<br />}<br />$stu1 = new Student('清华大学', '计算机', '张三');<br />$stu1->printInfo();<br />$stu2 = $stu1->copy();<br />$stu2->name = '李四';<br />$stu2->printInfo();<br />?><br />
这里可以看到,如果类的成员变量非常多,如果由外部创建多个新对象再一个个赋值,则效率不高代码冗余也容易出错,通过原型拷贝复制自身再进行微小修改就是另一个新对象了。
设计模式的第一部分,创建型模式就总结完了。下面还有两部分结构型设计模式和行为型设计模式稍后继续。