当前位置: 主页 > 编程知识 > Php编程 > 全面介绍php值对象模式设计

全面介绍php值对象模式设计

时间:2010-1-25来源:站长资讯网 点击:

另一个重要的概念是对象Monopoly中的租金支付。让我们首先写一个测试实例(测试引导开发)。下面的代码希望用来实现既定的目标。

function TestRent() {

$game = new Monopoly;

$player1 = new Player(‘Madeline’);

$player2 = new Player(‘Caleb’);

$this->assertEqual(1500, $player1->getBalance());

$this->assertEqual(1500, $player2->getBalance());

$game->payRent($player1, $player2, new Dollar(26));

$this->assertEqual(1474, $player1->getBalance());

$this->assertEqual(1526, $player2->getBalance());

}

根据这个测试代码,我们需要在Monopoly对象中增加payRent()的方法函数来实现一个Player对象去支付租金给另一个Player对象.

Class Monopoly {

// ...

/**

* pay rent from one player to another

* @param Player $from the player paying rent

* @param Player $to the player collecting rent

* @param Dollar $rent the amount of the rent

* @return void

*/

public function payRent($from, $to, $rent) {

$to->collect($from->pay($rent));

}

}

payRent()方法函数实现了两个player对象之间($from和$to)的租金支付。方法函数Player::collect()已经被定义了,但是Player::pay()必须被添加进去,以便实例$from通过pay()方法支付一定的Dollar数额$to对象中。首先我们定义Player::pay()为:

class Player {

// ...

public function pay($amount) {

$this->savings = $this->savings->add(-1 * $amount);

}

}

但是,我们发现在PHP中你不能用一个数字乘以一个对象(不像其他语言,PHP不允许重载操作符,以便构造函数进行运算)。所以,我们通过添加一个debit()方法函数实现Dollar对象的减的操作。

class Dollar {

protected $amount;

public function __construct($amount=0) {

$this->amount = (float)$amount;

}

public function getAmount() {

return $this->amount;

}

public function add($dollar) {

return new Dollar($this->amount + $dollar->getAmount());

}

public function debit($dollar) {

return new Dollar($this->amount - $dollar->getAmount());

}

}

引入Dollar::debit()后,Player::pay()函数的操作依然是很简单的。

class Player {

// ...

/**

* make a payment

* @param Dollar $amount the amount to pay

* @return Dollar the amount payed

*/

public function pay($amount) {

$this->savings = $this->savings->debit($amount);

return $amount;

}

}

Player::pay()方法返回支付金额的$amount对象,所以Monopoly::payRent()中的语句$to->collect($from->pay($rent))的用法是没有问题的。这样做的话,如果将来你添加新的“商业逻辑”用来限制一个player不能支付比他现有的余额还多得金额。(在这种情况下,将返回与player的账户余额相同的数值。同时,也可以调用一个“破产异常处理”来计算不足的金额,并进行相关处理。对象$to仍然从对象$from中取得$from能够给予的金额。)

注:术语------商业逻辑

在一个游戏平台的例子上提及的“商业逻辑”似乎无法理解。这里的商业的意思并不是指正常公司的商业运作,而是指因为特殊应用领域需要的概念。请把它认知为 “一个直接的任务或目标”,而不是“这里面存在的商业操作”。

所以,既然目前我们讨论的是一个Monopoly,那么这里的 “商业逻辑”蕴含的意思就是针对一个游戏的规则而说的。

站长资讯网
.
分页: [1] [2] [3] [4] [5]
TAG: php 值对象模式
推荐内容最近更新人气排行
关于我们 | 友情链接 | 网址推荐 | 常用资讯 | 网站地图 | RSS | 留言