Home > Backend Development > PHP Tutorial > PHP 设计模式之原型模式

PHP 设计模式之原型模式

WBOY
Release: 2016-06-20 13:02:00
Original
1059 people have browsed it

PHP 设计模式之原型模式

“原型模式其实就是从一个对象再创建另外一个可定制的对象,而且不需知道任何创建的细节。”

我们来看看基本的原型模式代码。

<?php /**
 * 原型模式
 *
 * 用原型实例指定创建对象的种类.并且通过拷贝这个原型来创建新的对象
 *
 */
abstract class Prototype {
       
    private$_id = null;
       
    public function __construct($id) {
        $this->_id = $id;
    }
       
    public function getID() {
        return $this->_id;
    }
       
    public function __clone() { // magic function
        $this->_id +=1;
    }
       
    public function getClone() {
        return clone $this;
    }
       
}
       
class ConcretePrototype extends Prototype {
           
}
       
$objPrototype = new ConcretePrototype(0);
       
$objPrototype1 = clone $objPrototype;
echo $objPrototype1->getID() . "<br>";
       
$objPrototype2 = $objPrototype;
echo $objPrototype2->getID() . "<br>";
       
$objPrototype3 = $objPrototype->getClone();
echo $objPrototype3->getID() . "<br>";
       
?>
Copy after login


Related labels:
php
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