Heim  >  Artikel  >  Backend-Entwicklung  >  PHP设计模式——原型模式_PHP教程

PHP设计模式——原型模式_PHP教程

WBOY
WBOYOriginal
2016-07-13 09:55:24661Durchsuche

PHP设计模式——原型模式

 

用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。Prototype模式允许一个对象再创建另外一个可定制的对象,根本无需知道任何如何创建的细节,通过将一个原型对象传给那个要发动创建的对象,这个要发动创建的对象通过请求原型对象拷贝它们自己来实施创建。它主要面对的问题是:“某些结构复杂的对象”的创建工作;由于需求的变化,这些对象经常面临着剧烈的变化,但是他们却拥有比较稳定一致的接口。

 

在php中,类已经实现了原型模式,php有个魔术方法__clone()方法,会克隆出一个这样的对象。

看一下UML类图:

\

 

角色分析:

1.抽象原型,提供了一个克隆的接口

2.具体的原型,实现克隆的接口

 

具体的代码:

 

/**抽象原型类
 * Class Prototype
 */
abstract class Prototype
{
   abstract function cloned();
}

/**具体原型类
 * Class Plane
 */
class Plane extends Prototype
{

    public $color;

    function Fly()
    {
        echo 飞机飞啊飞!
;
    }

    function cloned()
    {
        return clone $this;
    }
}

 

客户端测试代码:

 

header(Content-Type:text/html;charset=utf-8);
//------------------------原型模式测试代码------------------
require_once ./Prototype/Prototype.php;

$plane1=new Plane();
$plane1->color=Blue;

$plane2=$plane1->cloned();

$plane1->Fly();
$plane2->Fly();

echo plane1的颜色为:{$plane1->color}
;
echo plane2的颜色为:{$plane2->color}
;

这里只是介绍一下原型模式的核心思想,其实在实际开发中直接clone即可。

 

 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/991918.htmlTechArticlePHP设计模式——原型模式 用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。Prototype模式允许一个对象再创建另外一个...
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