PHP Design Patterns Prototype Pattern

不言
Release: 2023-03-24 09:56:02
Original
1749 people have browsed it

The content of this article is about the prototype mode of PHP design pattern, which has certain reference value. Now I share it with everyone. Friends in need can refer to it

Prototype It’s not difficult to understand.

To sum up, it is to create objects through a cloning method to save the complexity of creating objects.

It can be mainly used to prevent a lot of code redundancy caused by repeatedly creating objects.

The recording code is as follows:

<?php  
/** 抽象原型类 
 *  abstract Class Prototype 
 */  
abstract Class Prototype  
{  
    abstract function Cloned();  
}  
  
  
/** 英雄类 继承抽象类 
 *  Class Hero 
 */  
class Hero extends Prototype  
{  
    public $weapon; // 武器变量  
  
    function Create()  
    {  
        echo "英雄已经创建完成,手里拿着";  
    }  
  
    // 克隆方法  
    function Cloned()  
    {  
        return clone $this;// PHP clone方法  
    }  
}
Copy after login
<br/>
Copy after login
weapon = "琉璃琴"; // 添加武器  
  
// 第二次通过克隆一号英雄 得到二号英雄  
$hero2 = $hero1->Cloned();  
  
$hero1->Create();  
echo "=>{$hero1->weapon}<br/>";  
  
// 克隆 会将类里面的函数和变量复制一份  
$hero2->Create();  
echo "=>{$hero2->weapon}<br/>";
Copy after login



##The output result is:

The hero has been The creation is completed, holding the Liuli Qin in hand=>Liu Li Qin
The hero has been created, holding the Liu Li Qin

# Related recommendations:

PHP design pattern singleton pattern

PHP design pattern abstract factory

factory method of PHP design pattern

The above is the detailed content of PHP Design Patterns 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!