PHP design pattern-prototype Pattern
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 (); the echo plane1 color is: {$ plane1-> color}; the echo plane2 color 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.