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

Tags: 原型模式有什么用

分享到: