PHP design Pattern: Prototype Mode learning notes

Source: Internet
Author: User


The prototype pattern is actually similar to the factory pattern, which is used to create objects, except that they are different from the implementation of the factory pattern. The prototype pattern is to create a prototype object first, and then create a new object from the Clone prototype object. This eliminates the duplication of initialization when the class is created. The prototype pattern applies to the creation of large objects, because it costs a lot to create a large object. If you go to new every time, you will consume a lot of it, and the prototype mode needs to be copied from memory only.

Or continue with the example to show you

<?php/**  *  Abstract prototype role  */interface prototype {    public 
Function clone_obj (); /**  *  Specific prototype roles  */class concrete implements prototype{     
 private  $data;       public function __construct ($data)  {    
     $this->data =  $data; &NBSP;&NBSP;&NBSP;&NBSP}     public function get_data ()  {   
     return  $this->data; &NBSP;&NBSP;&NBSP;&NBSP}       public function clone_obj ()  { 
       /*          *  Deep Copy implementation          */        /*$ Serialize_obj = serialize ($this); //  Serialization          $clone _obj = unserialize ($serialize _obj);  //   Anti-serialization           return  $clone _obj;*/           return clone  $this; //  shallow copy    &nbsp}}/* *  *  Test deep copy of reference class  */class demo {    public  $arr; $demo  =
 new demo ();
$demo->arr = array (1,&NBSP;2);
$concrete  = new concrete ($demo);
$object 1 =  $concrete->clone_obj ();
Var_dump ($concrete->get_data ());
echo  ' <br /> ';
Var_dump ($object 1->get_data ());
echo  ' <br /> ';
Test deep copy $demo->arr = array (3, 4);
Var_dump ($concrete->get_data ());
echo  ' <br /> ';
Var_dump ($object 1->get_data ()); echo  ' <br /> ';?>

More detailed descriptions and examples

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.