其他语言

本类阅读TOP10

·基于Solaris 开发环境的整体构思
·使用AutoMake轻松生成Makefile
·BCB数据库图像保存技术
·GNU中的Makefile
·射频芯片nRF401天线设计的分析
·iframe 的自适应高度
·BCB之Socket通信
·软件企业如何实施CMM
·入门系列--OpenGL最简单的入门
·WIN95中日志钩子(JournalRecord Hook)的使用

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
设计模式PHP5实现之----原型(Prototype)

作者:未知 来源:月光软件站 加入时间:2005-5-13 月光软件站

<?php
/**
* 原型模式
*
* 允许一个对象再创建另外一个可定制的对象,
* 根本无需知道任何如何创建的细节,
* 工作原理是:通过将一个原型对象传给那个要发动创建的对象,
* 这个要发动创建的对象通过请求原型对象拷贝它们自己来实施创建
*
* @author doodoo<[email protected]>
*
*/
class Prototype{
 private $id = null,$name = null;
 public function __construct(){
  $this->id = "0";
  $this->name = "panwei";  
 }
  
 public function copy(Prototype $p){
  $q = new Prototype();
  $q->id = $p->id + 1;
  $q->name = "doodoo";
  return $q;
 }
}

$prototype = new Prototype();
$p2 = $prototype->copy($prototype);

print_r($prototype);
print_r($p2);

?>

其实PHP5内置有clone函数,这样的话我们的实现一下边的简单起来,以上代码可以修改成这样

<?php
/**
* 原型模式
*
* 允许一个对象再创建另外一个可定制的对象,
* 根本无需知道任何如何创建的细节,
* 工作原理是:通过将一个原型对象传给那个要发动创建的对象,
* 这个要发动创建的对象通过请求原型对象拷贝它们自己来实施创建
*
* @author doodoo<[email protected]>
*
*/
class Prototype{
 private $id = null,$name = null;
 public function __construct(){
  $this->id = "0";
  $this->name = "panwei";  
 }
  
 /**
 * 对象被clone的时候该方法将被调用
 */
 public function __clone(){
  $this->id ++;
  $this->name = "doodoo";
  return $q;
 }
}

$prototype = new Prototype();
$p2 = clone $prototype;

print_r($prototype);
print_r($p2);

?>

在PHP5中对原型模式的使用变成了对clone函数的使用及__clone()函数的实现。




相关文章

相关软件