还记得多莉吗?那只克隆羊。这里不深刻细节,关键点在于克隆。编程
基于现有对象经过克隆建立对象。设计模式
在软件开发过程当中,原型模式是一种建立型设计模式。当要建立的对象类型由原型实例肯定时,将经过克隆原型实例生成新对象。ui
简言之,原型模式容许你建立现有对象的副本并根据须要进行修改,而不是从头开始建立对象并进行设置。this
使用 PHP 的 clone 方法能够轻松实现spa
class Sheep设计
{对象
protected $name;开发
protected $category;get
public function __construct(string $name, string $category = 'Mountain Sheep')原型
{
$this->name = $name;
$this->category = $category;
}
public function setName(string $name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setCategory(string $category)
{
$this->category = $category;
}
public function getCategory()
{
return $this->category;
}
}
能够像下面这样克隆
$original = new Sheep('Jolly');
echo $original->getName(); // Jolly
echo $original->getCategory(); // Mountain Sheep
// Clone and modify what is required
$cloned = clone $original;
$cloned->setName('Dolly');
echo $cloned->getName(); // Dolly
echo $cloned->getCategory(); // Mountain sheep
此外,你能够使用魔术方法 **clone 来修改克隆行为。
当须要建立一个与已有对象相似的对象,或者当建立对象的成本比克隆更高时,使用原型模式。