原型模式

原型模式:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

原型模式类结构图:

原型模式类结构图

php实现:

<?php
interface Prototype {
    public function copy();
}

/** 
 * 具体原型角色 
 */
class ConcretePrototype implements Prototype{

    private  $_name;

    public function __construct($name) {
        $this->_name = $name;
    }

    public function setName($name) {
        $this->_name = $name;
    }

    public function getName() {
        return $this->_name;
    }

    public function copy() {
       /** 深拷贝 */
       return  clone  $this;
       /** 浅拷贝 */
       //return  $this;     
    }
}


class Client {
    public static function run() {
        $object1 = new ConcretePrototype(11);
        $object_copy = $object1->copy();

        var_dump($object1->getName());
        var_dump($object_copy->getName());

        $object1->setName(22);
        var_dump($object1->getName());
        var_dump($object_copy->getName());
    }
}

Client::run();
?>

  执行结果:

php prototype.php
int(11)
int(11)
int(22)
int(11)

原文地址:https://www.cnblogs.com/zhutianpeng/p/4238650.html