·天新网首页·加入收藏·设为首页
首页|笔记本|手机|数码相机|摄像机|MP3/MP4|主板|内存|显示器|办公|打印机|下载|开发|汽车|学院|业界
硬件|台式机|数码|数字家庭|投影仪|GPS/CPU|显卡|硬盘|服务器|网络|一体机|驱动|源码|游戏|考试|报价
您现在的位置:天新网 > 软件开发 > Web开发 > PHP开发
php教程:php设计模式介绍之值对象模式
http://dev.21tx.com 2008年04月11日 phpchina forest

上一页 1 2 3 4 5 下一页

详细例子

让我们在一下更加复杂的例子中查看值对象模式的功能。

让我们开始实现一个的基于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的功能比较简单。构造器创建一个Dollar类的实例$go_amount,设定为200,实例go_amount常常被passtGo()函数调用,它带着一个player参数,并让对象player的函数collect为player机上200美元.

Player类的声明请看下面代码,Monoplay类调用带一个Dollar参数的Player::collect()方法。然后把Dollar的数值加到Player的现金余额上。另外,通过判断Player::getBalance()方法函数返回来的余额,我们可以知道使访问当前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();
}
}

上边已经给出了一个Monopoly和Player类,你现在可以根据目前声明的几个类定义进行一些测试了。

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这个测试代码,代码的运行是没有问题的。现在可以添加一些新的功能。

上一篇: 轻松修复Discuz!数据库
下一篇: PHP使用zlib扩展实现页面GZIP压缩输出

上一页 1 2 3 4 5 下一页

Google
 
热点文章
关于我们 | 联系我们 | 广告服务 | 工作机会 | 版权声明 | 欢迎投稿 | 网站地图
Copyright © 2000-2008 , www.21tx.com , All Rights Reserved .
© 晨新科技 版权所有 Created by TXSite.net