当前位置:首页 > PHP教程 > php高级应用 > 列表

原型模式有什么用?

发布:smiling 来源: PHP粉丝网  添加日期:2020-02-17 19:06:32 浏览: 评论:0 

原型模式(Prototype)

Prototype原型模式是一种创建型设计模式,Prototype模式允许一个对象再创建另外一个可定制的对象,根本无需知道任何如何创建的细节,工作原理是:通过将一个原型对象传给那个要发动创建的对象,这个要发动创建的对象通过请求原型对象拷贝它们自己来实施创建。

解决什么问题

它主要面对的问题是:“某些结构复杂的对象”的创建工作;由于需求的变化,这些对象经常面临着剧烈的变化,但是他们却拥有比较稳定一致的接口。

使用php提供的clone()方法来实现对象的克隆,所以Prototype模式实现一下子变得很简单。并可以使用php的__clone() 函数完成深度克隆。

代码实例:

  1. <?php 
  2.  
  3. //定义原型类接口 
  4.  
  5. interface prototype{ 
  6.  
  7. public function copy(); 
  8.  
  9.  
  10. //一个具体的业务类并实现了prototype 接口 
  11.  
  12. //以一个文本的读写操作类为例 
  13.  
  14. class text implements prototype{ 
  15.  
  16. private $_fileUrl
  17.  
  18. public function __construct($fileUrl){ 
  19.  
  20. $this->_fileUrl = $fileUrl
  21.  
  22.  
  23. public function write($content){ 
  24.  
  25. file_put_contents($this->_fileUrl, $content); 
  26.  
  27.  
  28. public function read(){ 
  29.  
  30. return file_get_contents($this->_fileUrl); 
  31.  
  32.  
  33. public function copy(){ 
  34.  
  35. return clone $this
  36.  
  37.  
  38. /* 可以使用php的__clone() 函数完成深度克隆 */ 
  39.  
  40. public function __clone(){ 
  41.  
  42. echo 'clone...'
  43.  
  44.  
  45.  
  46. $texter1 = new text('1.txt'); 
  47.  
  48. $texter1->write('test...'); 
  49.  
  50. //获得一个原型 
  51.  
  52. $texter2 = $texter1->copy(); 
  53.  
  54. echo $texter2->read(); 

Tags: 原型模式有什么用

分享到: