<?php
/**
* 抽象原型角色
*/
interface Prototype {
public function clone_obj();
}
/**
* 具体原型角色
*/
class Concrete implements Prototype{
private $data;
public function __construct($data) {
$this->data = $data;
}
public function get_data() {
return $this->data;
}
public function clone_obj() {
/*
* 深拷贝实现
*/
/*$serialize_obj = serialize($this); //
序列化
$clone_obj = unserialize($serialize_obj); // 反序列化
return $clone_obj;*/
return clone $this; // 浅拷贝
}
}
/**
* 测试深拷贝用的引用类
*/
class Demo {
public $arr;
}
$demo = new Demo();
$demo->arr = array(1, 2);
$concrete = new Concrete($demo);
$object1 = $concrete->clone_obj();
var_dump($concrete->get_data());
echo '<br />';
var_dump($object1->get_data());
echo '<br />';
//测试深拷贝
$demo->arr = array(3, 4);
var_dump($concrete->get_data());
echo '<br />';
var_dump($object1->get_data());
echo '<br />';
?>