目录

代码示例

<?php

namespace DesignPattern;

/**
 * Description of Prototype
 *
 * @author jm
 */
class Prototype
{
    //put your code here
    public static function main()
    {
        $employer = new Employer();
        $employer->setInfo("男", 25,'JM');
        $employer->setExperience("2010-2014","B公司");

        $employer2 = clone $employer;
        $employer2->setInfo("男", 27,"Tsing");
        $employer2->setExperience("2009-2016","A公司");

        $employer->display();
        $employer2->display();        
    }
    
}

class Company
{
    private $company;

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

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

class Employer
{
    private $name;
    private $sex;
    private $age;
    private $timeArea;
    private $company;

    function __construct()
    {
        $this->company = new Company();
        //可能更多初始化信息和操作
    }

    public function setInfo($sex, $age,$name)
    {
        $this->name = $name;
        $this->sex = $sex;
        $this->age = $age;
    }

    public function setExperience($timeArea, $company)
    {
        $this->timeArea = $timeArea;
        $this->company->setName($company);
    }

    public function display()
    {
        echo $this->name." ".$this->sex." ".$this->age."\n";
        echo $this->timeArea." ".$this->company->getName()."\n";
    }

    // 对引用执行深复制
    function __clone()
    {
        $this->company = clone $this->company;
    }
}

Prototype::main();



输出:

JM 男 25
2010-2014 B公司
Tsing 男 27
2009-2016 A公司

小结

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

原型模式其实就是从一个对象再创建另外一个可定制的对象,而且不需要知道任何创建的细节。

一般在初始化的信息不发生变化的情况下,克隆是最好的办法。既隐藏了对象创建的细节,又对性能是大大的提高。

注:对象创建初始化复杂,性能要求高的,可以考虑原型创建模式,减少开销提高性能。


本文部分收藏来自互联网,仅用于学习研究,著作权归原作者所有,如有侵权请联系删除

markdown 9ong@TsingChan