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; } }
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} ;