创建型设计模式 - 原型 Prototype
作者:菜皮日记
- 2023-09-08 北京
本文字数:1201 字
阅读完需:约 4 分钟
简介
原型模式支持按照一个对象为模板,创建出另一个一模一样的对象。
简单说就是把 A 对象的属性,都赋值到 B 上,注意必须是深拷贝,即 clone 后的 AB 关联的对象是不同的对象。
角色
抽象原型类
定义 clone 方法
具体实现类
实现 clone 方法
类图
类图
代码
class Prototype
{
public $primitive;
public $component;
public $circularReference;
public function __clone()
{
$this->component = clone $this->component;
$this->circularReference = clone $this->circularReference;
$this->circularReference->prototype = $this;
}
}
class ComponentWithBackReference
{
public $prototype;
public function __construct(Prototype $prototype)
{
$this->prototype = $prototype;
}
}
function clientCode()
{
$p1 = new Prototype();
$p1->primitive = 245;
$p1->component = new \DateTime();
$p1->circularReference = new ComponentWithBackReference($p1);
$p2 = clone $p1;
if ($p1->primitive === $p2->primitive) {
echo "Primitive field values have been carried over to a clone. Yay!\n";
} else {
echo "Primitive field values have not been copied. Booo!\n";
}
if ($p1->component === $p2->component) {
echo "Simple component has not been cloned. Booo!\n";
} else {
echo "Simple component has been cloned. Yay!\n";
}
if ($p1->circularReference === $p2->circularReference) {
echo "Component with back reference has not been cloned. Booo!\n";
} else {
echo "Component with back reference has been cloned. Yay!\n";
}
if ($p1->circularReference->prototype === $p2->circularReference->prototype) {
echo "Component with back reference is linked to original object. Booo!\n";
} else {
echo "Component with back reference is linked to the clone. Yay!\n";
}
}
clientCode();
复制代码
output:
Primitive field values have been carried over to a clone. Yay!
Simple component has been cloned. Yay!
Component with back reference has been cloned. Yay!
Component with back reference is linked to the clone. Yay!
复制代码
划线
评论
复制
发布于: 刚刚阅读数: 5
菜皮日记
关注
全干程序员 2018-08-08 加入
还未添加个人简介
评论