关于后端:创建型设计模式原型-Prototype

45次阅读

共计 1498 个字符,预计需要花费 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!

正文完
 0