PHP design mode-prototype mode

Source: Internet
Author: User
Statement: This series of blog reference "Big Talk design mode", author Geoscience.

Use the prototype instance to specify the kind of object to create and create a new object by copying the prototypes. The prototype mode allows an object to create another customizable object without having to know any details of how to create it, by passing a prototype object to the object that is being created, which creates the object by requesting the prototype object to copy themselves to implement the creation. The main problem is the creation of "some complex objects", which often face drastic changes due to the change of requirements, but they have more stable and consistent interfaces.


In PHP, the class has implemented prototype mode, PHP has a magic Method __clone () method, will clone a such object.

Take a look at the UML class diagram:


Role Analysis:

1. Abstract prototype, provides a cloned interface

2. Specific prototypes to implement the cloned interface


The specific code:

/** Abstract Prototype Classes * Class Prototype */abstract class prototype{   abstract function cloned ();} /** Concrete Prototype class * Class Plane */class Plane extends prototype{public    $color;    function Fly ()    {        echo plane fly, fly!
"; } function cloned () { return clone $this; }}

Client Test Code:

Header ("Content-type:text/html;charset=utf-8");//------------------------prototype mode test code------------------require_ Once "./prototype/prototype.php"; $plane 1=new Plane (); $plane 1->color= "Blue"; $plane 2= $plane 1->cloned (); $ Plane1->fly (); $plane 2->fly (); echo "Plane1 color: {$plane 1->color}
The color of "echo" Plane2 is: {$plane 2->color}
";

Here is just a prototype model of the core idea, in fact, in the actual development of the direct clone can be.


PHP Object-oriented design pattern

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.