A brief analysis of php prototype mode, a brief analysis of php prototype_PHP tutorial

WBOY
Release: 2016-07-13 10:13:18
Original
1006 people have browsed it

A brief analysis of php prototype pattern, a brief analysis of php prototype

Prototype mode:

Use a prototype instance to specify the type of object to be created, and create new objects by copying this prototype.
Application scenario: The class has a lot of resources, performance and security requirements, and is generally used in combination with factory methods.

Copy code The code is as follows:

/**
* Prototype mode
​*/
//Declare an interface that clones itself
interface Prototype {
Function copy();
}
//The product needs to implement the operation of cloning itself
class Student implements Prototype {
//For the sake of simplicity, get set
is not used here Public $school;
Public $major;
       public $name;
Public function __construct($school, $major, $name) {
$this->school = $school;
                   $this->major = $major;
                    $this->name = $name;
}
Public function printInfo() {
                       printf("%s,%s,%sn", $this->school, $this->major, $this->name);
}
Public function copy() {
              return clone $this;
}
}
$stu1 = new Student('Tsinghua University', 'Computer', 'Zhang San');
$stu1->printInfo();
$stu2 = $stu1->copy();
$stu2->name = '李思';
$stu2->printInfo();
?>

As you can see here, if a class has a lot of member variables, if multiple new objects are created externally and assigned one by one, the efficiency will be inefficient and the code will be redundant and error-prone. Just copy itself through the prototype copy and then make minor modifications. Another new object.

This concludes the first part of design patterns, creational patterns. There are two parts below, structural design patterns and behavioral design patterns, which will be continued later.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/917027.htmlTechArticleA brief analysis of the php prototype pattern, a brief analysis of the php prototype prototype pattern: Use the prototype instance to specify the type of object to be created, and pass Copy this prototype to create new objects. Application scenarios: Class resources...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!