layout | title | date | author | desc | in_head |
---|---|---|---|---|---|
post
|
PHP设计模式之原型模式
|
2018-03-08 10:00:02 +0800
|
南丞
|
设计模式(Design Pattern)是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设计模式是为了可重用代码、让代码更容易被他人理解、保证代码可靠性。设计模式于己于他人于系统都是多赢的;设计模式使代码编制真正工程化;设计模式是软件工程的基石脉络,如同大厦的结构一样。
|
<style> .article-content p{ text-indent: 2em; line-height: 1.75rem; }</style>
|
原型模式
<?php
header("Content-type: text/html; charset=utf-8");
/**
* 抽象 原型类
*/
abstract class Prototype
{
abstract function cloned(); //克隆方法
}
/**
* 具体化 原型类
*/
class Plane extends Prototype
{
public $color; //测试的成员属性
public function cloned()
{
// clone 关键字
return clone $this;
}
}
# 测试
$res1 = new Plane();
$res1->color = '蓝色'; // 赋值成员属性
$res2 = $res1->cloned(); // 克隆一个实例
echo "res1的颜色为:{$res1->color}<br/>";
echo "res2的颜色为:{$res2->color}<br/>";