PHP Design Patterns - Prototype Pattern_PHP Tutorial

WBOY
Release: 2016-07-13 09:55:24
Original
705 people have browsed it

PHP Design Pattern - Prototype Pattern

Use prototype instances to specify the types of objects to be created, and create new objects by copying these prototypes. The Prototype pattern allows an object to create another customizable object without knowing any details of how to create it. By passing a prototype object to the object that initiates creation, the object that initiates creation copies itself by requesting the prototype object. to implement creation. The main problem it faces is: the creation of "some objects with complex structures"; due to changes in requirements, these objects often face drastic changes, but they have relatively stable and consistent interfaces.

In PHP, classes have implemented prototype mode. PHP has a magic method __clone() method, which will clone such an object.

Look at the UML class diagram:

Character Analysis:

1. Abstract prototype provides a cloned interface

2. Specific prototype, implement clone interface

Specific code:

/**抽象原型类
 * Class Prototype
 */
abstract class Prototype
{
   abstract function cloned();
}

/**具体原型类
 * Class Plane
 */
class Plane extends Prototype
{

    public $color;

    function Fly()
    {
        echo 飞机飞啊飞!
;
    }

    function cloned()
    {
        return clone $this;
    }
}
Copy after login

Client test code:

header(Content-Type:text/html;charset=utf-8);
//------------------------原型模式测试代码------------------
require_once ./Prototype/Prototype.php;

$plane1=new Plane();
$plane1->color=Blue;

$plane2=$plane1->cloned();

$plane1->Fly();
$plane2->Fly();

echo plane1的颜色为:{$plane1->color}
;
echo plane2的颜色为:{$plane2->color}
;
Copy after login

Here we just introduce the core idea of ​​the prototype mode. In fact, in actual development, you can just clone it directly.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/991918.htmlTechArticlePHP Design Pattern - Prototype pattern uses prototype instances to specify the types of objects to be created, and creates new ones by copying these prototypes object. Prototype mode allows one object to create another...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template