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

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

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

详细例子:

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

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

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