欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

php設(shè)計模式介紹之值對象模式第3/5頁

 更新時間:2008年04月13日 22:10:17   作者:  
在所有的最簡單的程序中,大多數(shù)對象都有一個標(biāo)識,一個重要的商業(yè)應(yīng)用對象,例如一個Customer或者一個SKU,有一個或者更多的屬性---id,name,email地址,這樣可以把它從同一個類的其他實例區(qū)分開來。此外,對象有一個恒定的標(biāo)識:它是貫穿于整個應(yīng)用程序的一個唯一的標(biāo)識,對于程序員來說,”customer A”在任何地方就是”customer A”,并且只要你的程序在持續(xù)運行時"customer A"仍然是"customer A"。 但是一個對象不需要有一個標(biāo)識。有些對象僅僅是為了描述其他對象的屬性。

詳細(xì)例子:

讓我們在一下更加復(fù)雜的例子中查看值對象模式的功能。

讓我們開始實現(xiàn)一個的基于PHP5中Dollar類中的一個Monopoly游戲。

第一個類Monopoly的框架如下:

class Monopoly {
protected $go_amount;
/**
* game constructor
* @return void
*/
public function __construct() {
$this->go_amount = new Dollar(200);
}
/**
* pay a player for passing 揋o?/span>
* @param Player $player the player to pay
* @return void
*/
public function passGo($player) {
$player->collect($this->go_amount);
}
}
目前,Monopoly的功能比較簡單。構(gòu)造器創(chuàng)建一個Dollar類的實例$go_amount,設(shè)定為200,實例go_amount常常被passtGo()函數(shù)調(diào)用,它帶著一個player參數(shù),并讓對象player的函數(shù)collect為player機上200美元.

Player類的聲明請看下面代碼,Monoplay類調(diào)用帶一個Dollar參數(shù)的Player::collect()方法。然后把Dollar的數(shù)值加到Player的現(xiàn)金余額上。另外,通過判斷Player::getBalance()方法函數(shù)返回來的余額,我們可以知道使訪問當(dāng)前Player和Monopoly對象實例是否在工作中。

class Player {
protected $name;
protected $savings;
/**
* constructor
* set name and initial balance
* @param string $name the players name
* @return void
*/
public function __construct($name) {
$this->name = $name;
$this->savings = new Dollar(1500);
}
/**
* receive a payment
* @param Dollar $amount the amount received
* @return void
*/
public function collect($amount) {
$this->savings = $this->savings->add($amount);
}
* return player balance
* @return float
*/
public function getBalance() {
return $this->savings->getAmount();
}
}
上邊已經(jīng)給出了一個Monopoly和Player類,你現(xiàn)在可以根據(jù)目前聲明的幾個類定義進行一些測試了。

MonopolyTestCase的一個測試實例可以像下面這樣寫:

class MonopolyTestCase extends UnitTestCase {
function TestGame() {
$game = new Monopoly;
$player1 = new Player(‘Jason');
$this->assertEqual(1500, $player1->getBalance());
$game->passGo($player1);
$this->assertEqual(1700, $player1->getBalance());
$game->passGo($player1);
$this->assertEqual(1900, $player1->getBalance());
}
}
如果你運行MonopolyTestCase這個測試代碼,代碼的運行是沒有問題的?,F(xiàn)在可以添加一些新的功能。

相關(guān)文章

最新評論