PHP design pattern-Prototype pattern

Source: Internet
Author: User
PHP design pattern-Prototype pattern statement: This series of blog reference material "big talk design pattern", author Cheng Jie.

Use a prototype instance to specify the type of the object to be created, and copy the prototype to create a new object. The Prototype mode allows an object to create another custom object. you do not need to know how to create any details. by passing a Prototype object to the object to be created, the objects to be created are created by requesting the prototype objects to copy themselves. It mainly faces the following problems: the creation of "some objects with complex structures"; these objects are often subject to drastic changes due to changes in requirements, however, they have stable and consistent interfaces.


In php, the class has implemented the prototype mode. php has a magic method _ clone () to clone an object like this.

Take a look at the UML class diagram:


Role Analysis:

1. abstract prototype, providing a clone interface

2. the specific prototype implements the clone interface.


Specific code:

/** Abstract Prototype Class * class Prototype */abstract Class Prototype {abstract function cloned ();} /** Specific Prototype Class * class Plane */Class Plane extends Prototype {public $ color; function Fly () {echo "!
";} Function cloned () {return clone $ this ;}}

Client Test code:

Header ("Content-Type: text/html; charset = utf-8"); // ------------------------ prototype mode test code ------------------ require_once ". /Prototype. php "; $ plane1 = new Plane (); $ plane1-> color =" Blue "; $ plane2 = $ plane1-> cloned (); $ plane1-> Fly (); $ plane2-> Fly (); echo "the color of plane1 is: {$ plane1-> color}
"; Echo" the color of plane2 is: {$ plane2-> color}
";

Here is just a brief introduction to the core idea of the prototype mode. In fact, you can simply clone it in actual development.


PHP object-oriented design model

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.