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

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

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

詳細(xì)例子:

讓我們?cè)谝幌赂訌?fù)雜的例子中查看值對(duì)象模式的功能。

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

第一個(gè)類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的功能比較簡(jiǎn)單。構(gòu)造器創(chuàng)建一個(gè)Dollar類的實(shí)例$go_amount,設(shè)定為200,實(shí)例go_amount常常被passtGo()函數(shù)調(diào)用,它帶著一個(gè)player參數(shù),并讓對(duì)象player的函數(shù)collect為player機(jī)上200美元.

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

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)給出了一個(gè)Monopoly和Player類,你現(xiàn)在可以根據(jù)目前聲明的幾個(gè)類定義進(jìn)行一些測(cè)試了。

MonopolyTestCase的一個(gè)測(cè)試實(shí)例可以像下面這樣寫:

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());
}
}
如果你運(yùn)行MonopolyTestCase這個(gè)測(cè)試代碼,代碼的運(yùn)行是沒有問題的?,F(xiàn)在可以添加一些新的功能。

相關(guān)文章

最新評(píng)論