快速业务通道

php设计模式介绍之规范模式

作者 佚名技术 来源 NET编程 浏览 发布时间 2012-05-22
h) {
$key = (int)$month - 1;
if (array_key_exists($key, $this->avg_temps)) {
return $this->avg_temps [$key];
}
}
}

最后,一次旅行(类Trip)就由一个旅行者(类 Traveler),一个目的地(类Destination)和一个日期(a Date)联合组成。

class Trip {
public $date;
public $traveler;
public $destination;
}

给出上面这些对象,你就可以通过Trip::date得到旅行的月份,并且你能够比较目的 地的月平均温度和旅行者期望的最低温度。(这个比较可能不是特别的复杂,但是你还是需要你自己亲 自去实现)

让我们看看如何用规范模式实现“温暖目的地”的商业逻辑,并且看看如 何应用这个模式来验证每一个目的地并选择出所有合适的目的地。

样本代码

规范模式的 核心是一个带有IsSatisfiedBy()方法的对象,IsSatisfiedBy()方法接收一个变量来评估并且返回一个 基于规范标准的布尔值。

php设计模式介绍之规范模式

“目的地是足够温暖的”的标准可能就是:

class TripRequiredTemperatureSpecification {
public function isSatisfiedBy($trip) {
$trip_temp = $trip->destination->getAvgTemPByMonth(
date(‘m’, $trip->date));
return ($trip_temp >= $trip->traveler ->min_temp);
}
}

下面是一些测试,用来检验这个规范是如何工作的。

一个最初的个体测试事例提供了一些目的地来一起工作:

class TripSpecificationTestCase extends UnitTestCase {
protected $destinations = array();
function setup() {
$this->destinations = array(
‘Toronto’ => new Destination(
array(24, 25, 33, 43, 54, 63, 69, 69, 61, 50, 41, 29))
,’Cancun’ => new Destination(
array(74, 75, 78, 80, 82, 84, 84, 84, 83, 81, 78, 76))
);
}
}

(构造这些目的地(Destination)需要在实 例化的时候输入一个包含每月平均温度的数组。做为一个美国的作者,在这些例子中我选择了华氏温度 。对应的,Vicki期望的华氏温度70度等价于摄氏温度21度)

下一个测试构建了一个旅行者 (Traveler),并且设置了它的首选最低温度和旅行日期同时也选择了一个目的地。这最初的组合 “最低温度70度(华氏温度),目的地多伦多(Toronto),日期二月中旬”会和期望的一样 ,是不能通过的。

class TripSpecificationTestCase extends UnitTestCase {
// ...
function TestTripTooCold() {
$vicki = new Traveler;
$vicki->min_temp = 70;
$toronto = $this->destinations[‘Toronto’];
$trip = new Trip;
$trip->traveler = $vicki;
$trip->destination = $toronto;
$trip- >date = mktime(0,0,0,2,11,2005);
$warm_enough_check = new TripRequiredTemperatureSpecification;
$this->assertFalse($warm_enough_check- >isSatisfiedBy($trip));
}
}

但是,接下来的这个组合“70度,二 月中旬,Cancun ”就会通过,和我们期望的一样。

class TripSpecificationTestCase extends UnitTestCase {
// ...
function TestTripWarmEnough() {
$vicki = new Traveler;
$vicki->min_temp = 70;
$cancun = $this->destinations[‘Cancun’];
$trip = new Trip;
$trip->traveler = $vicki;
$trip->destination = $cancun;
$trip->date = mktime(0,0,0,2,11,2005);
$warm_enough_check = new TripRequiredTemperatureSpecification;
$this->assertTrue($warm_enough_check- >isSatisfiedBy($trip));
}
}

参数化规范

Trip Required Temperature Specification必须很熟悉Trip对象的结构,并且钻研Trip对象的三个

凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!

分享到: 更多

Copyright ©1999-2011 厦门凌众科技有限公司 厦门优通互联科技开发有限公司 All rights reserved

地址(ADD):厦门软件园二期望海路63号701E(东南融通旁) 邮编(ZIP):361008

电话:0592-5908028 传真:0592-5908039 咨询信箱:web@lingzhong.cn 咨询OICQ:173723134

《中华人民共和国增值电信业务经营许可证》闽B2-20100024  ICP备案:闽ICP备05037997号