用原型實例指定創建對象的種類,並且通過拷貝這些原型創建新的對象。
UML結構圖:
當需要靈活創建參數化對象但又不想使用new操作符時,就可以使用Prototype模式。使用抽象的clone()方法和一些實現clone()的子類創建一個父類,這樣就可以創建對象了。每個子類都包含一個實例化的Prototype對象,調用新實例時,它複製本身。這樣就可以很容易很靈活的創建對象。
<?php
abstract class CarPrototype {
protected $model;
protected $color;
abstract function __clone();
function getModel() {
return $this->model;
}
function getColor() {
return $this->color;
}
function setColor($colorIn) {
$this->color = $colorIn;
}
}
class DodgeCarPrototype extends CarPrototype {
function __construct() {
$this->model = 'Dodge Magnum';
}
function __clone() {
}
}
class SubaruCarPrototype extends CarPrototype {
function __construct() {
$this->model = 'Subaru Outback';
}
function __clone() {
}
}
?>
下面的代碼是用於測試前面的類。首先它創建兩個Prototype對象作爲展示的汽車,然後複製其中一個對象類滿足客戶,並可通過統一的界面來挑選顏色。
<?php
include_once('CarPrototype.class.php');
$dodgeProto= new DodgeCarPrototype();
$subaruProto = new SubaruCarPrototype();
echo 'Which car do you want? <br />';
$customerDecision = 'Subaru';
if( $customerDecision == 'Subaru' ){
$customersCar = clone $subaruProto;
} else {
$customersCar = clone $dodgeProto;
}
echo $customersCar->getModel().'<br />';
echo 'What color do you want?<br />';
$customersCar->setColor('red');
echo 'Fine, we will paint your '.$customersCar->getModel().
' '.$customersCar->getColor().'.<br />';
?>
前面的代碼將得到下面的消息:
Which car do you want?
Subaru Outback
What color do you want?
Fine, we will paint your Subaru Outback red.