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

“目的地是足够温暖的”的标准可能就是:
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)); } }
出处:
责任编辑:bluehearts
上一页 php设计模式介绍之规范模式 [1] 下一页 php设计模式介绍之规范模式 [3]
◎进入论坛网络编程版块参加讨论
|