PHP design pattern-detailed explanation of the use and function of prototype pattern

黄舟
Release: 2023-03-14 09:56:02
Original
1112 people have browsed it

Prototype Pattern (Prototype Pattern): Similar to Factory Pattern, both are used to create objects. Use cloning to generate a large object to reduce the overhead of initialization and other operations during creation

Why is the prototype mode needed

1. Sometimes, we need to create multiple similar large objects . If you pass the new object directly, the overhead is very high, and you have to perform repeated initialization work after new. It is possible to encapsulate the initialization work, but for the system, whether you encapsulate it or not, the initialization work still has to be performed.
2, the prototype mode is different. The prototype mode first creates a prototype object, and then creates a new object by cloning the prototype object. This avoids repeated initialization work, and the system only needs a memory copy.

<?php
/**
* 原型模式
*
* @author webff
*/
/**

//声明一个克隆自身的接口
interface Prototype {
    function copy(); 
}   

//产品要实现克隆自身的操作
class Student implements Prototype {
    //简单起见,这里没有使用get set
    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(&#39;清华大学&#39;, &#39;计算机&#39;, &#39;张三&#39;);
$stu1->printInfo();

$stu2 = $stu1->copy();
$stu2->name = &#39;李四&#39;;
$stu2->printInfo();

?>
Copy after login

You can see here that if a class has a lot of members variables, and if multiple new objects are created externally and assigned values ​​one by one, the efficiency will be inefficient and the code will be redundant and error-prone. Copying itself through a prototype copy and then making minor modifications becomes a new object.

The above is the detailed content of PHP design pattern-detailed explanation of the use and function of prototype pattern. For more information, please follow other related articles on the PHP Chinese website!

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