Heim  >  Artikel  >  Backend-Entwicklung  >  PHP 设计模式之原型模式

PHP 设计模式之原型模式

WBOY
WBOYOriginal
2016-06-20 13:02:001004Durchsuche

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>";
       
?>


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn