我正在做一个项目,要求我根据购买的租金生成报告。我必须对每种类型的租金进行计数,然后将相应的总数相加。目前,我正在使用一个切换块来根据当前租金确定要采取的操作。但是,据我了解,这违反了开放/封闭原则,因为每次添加新的租用时我都必须修改开关块。我想让它符合OCP,但是我不确定该怎么做。下面是我的代码:
public function generateReport($rentals)
{
$type_1_count = 0;
$type_2_count = 0;
$type_3_count = 0;
$type_1_sum = 0;
$type_2_sum = 0;
$type_3_sum = 0;
foreach ($rentals as $rental) {
switch ($rental->type) {
case 'TYPE_1':
$type_1_count++;
$type_1_sum += $rental->price;
break;
case 'TYPE_2':
$type_2_count++;
$type_2_sum += $rental->price;
break;
case 'TYPE_3':
// some of the rentals include other rentals which must be accounted for
$type_1_count++;
$type_1_sum += $rental->price / 2;
$type_3_count++;
$type_3_sum += $rental->price / 2;
break;
default:
echo 'Rental Not Identified';
}
}
return compact('type_1_count', 'type_2_count', 'type_3_count', 'type_1_sum', 'type_2_sum', 'type_3_sum');
}
我正在根据所选情况修改共享状态变量。我回顾了许多OCP示例,但所有示例均显示了如何执行操作或返回值,但是我需要修改共享状态。重构此代码使其更符合OCP的最佳方法是什么?
您可以使用关联数组。您只需要确保先设置变量即可。像这样:
$all_rentals = [];
foreach ($rentals as $rental) {
// make sure the variable has a default value
if(!isset($all_rentals[$rental->type."_count"]) {
$all_rentals[$rental->type."_count"] = 0;
$all_rentals[$rental->type."_sum"] = 0;
}
$all_rentals[$rental->type."_count"]++;
$all_rentals[$rental->type."_sum"] += $rental->price;
}
...
这样,您无需修改任何现有代码即可添加新值(租用类型)>>