首页  韩国资源  酷站加油  我的展厅  设计名站  古典元素  推荐下载  设计欣赏  每周专访  招募精英  人才专区  网页教程  平面设计  编程开发  设计竞赛
当前位置:首页 > 编程开发 > PHP教程 > 正文
Google
php设计模式介绍之值对象模式
来源:phpchina 2008年04月14日 08:37 网友评论:0条 点击:

另一个重要的概念是对象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] 下一页 尾页
上一篇:php设计模式介绍之编程惯用法   下一篇:php设计模式介绍之导言
收藏此页】【打印】【关闭
 相关文章  我要点评
·Apache与PHP的整合过程
·php设计模式介绍之伪对象模式
·php设计模式介绍之注册模式
·php设计模式介绍之单件模式
·PHP程序61条面向对象分析设计的原则
·PHP5程序中新增加日期(date)函数的常量
·PHP程序开发中的中文编码问题
·正确理解PHP程序错误信息的表示含义

免责声明:本站刊载此文不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。对本文有任何异议,请联络:68design#163.com
转载要求:作者及来源信息必需保留。转载之图片、文件,链接请不要盗链到本站,且不准打上各自站点的水印。



关于我们 | 在线反馈 | 广告报价 | 友情链接 | 联系我们 | 免责声明 | 在线投稿 | 网站地图
Copyright © 2003-2007 68design.net, All Rights Reserve 【找网页设计师,当然上网页设计师联盟】