我遇到这种情况:
用户可以选择3种产品,A,B或C,如图中所示。用户单击其中一个产品后,他将被重定向到注册表单,其中必须包含一些数据,包括x和y。如果所选产品以及x和y的值不正确,则会启动错误。如果输入的数据正确,则执行其他一些操作。我试图实现这个控件,但我不确定这是最好的解决方案。
if ($product==("A") && x < 10 && y <= 2)
{
price = 10;
}
else if ($product ==("B") && x < 50 && y <= 10 && y >2)
{
price = 20;
}
else if ($product ==("C") && x < 250 && y <=50)
{
price = 30;
}
答案 0 :(得分:2)
这里的“面向对象”方法是避免你实现的“告诉不要问”模式。
含义:你在“询问”某些属性;这样你的代码就可以根据它做出决定。解决方法是:不要这样做!
相反:您创建了一个“基础”产品类,它提供的方法包括 isXinRange()和 isYinRange()。然后,每个产品都有不同的子类;和 AProduct.isXinRange 检查x < 10
...
含义:您的范围检查分为三个不同的类别!
而不是将所有内容都放在“一个”比较中,而是执行以下操作:
someProduct = generateProductFor(stringFromUser)
someProduct.isXinRange()
是否为用户提供的X提供了真实(我对PHP不太熟悉,对于我的半伪半java编码风格很遗憾)
答案 1 :(得分:0)
//not a short solution or a fast one but has some advantages:
//1. has some logic shared by GhostCat but in a interative way
//2. takes in consideration of multiple cases of A,B,C... in case you load your data from DB
//3. separates raw data from logic, easy to edit later and expand
$data = array(
'A' => array(
'variables' => array(
'x' => array(
10 => '<'
),
'y' => array(
2 => '<='
),
),
'function' => 'functionA',
),
'B' => array(
'variables' => array(
'x' => array(
50 => '<'
),
'y' => array(
2 => '>'
),
),
'function' => 'functionB',
),
'C' => array(
'variables' => array(
'x' => array(
250 => '<'
),
'y' => array(
50 => '<='
),
),
'function' => 'functionC',
),
);
//
foreach ($data[$product]['variables'] as $variable => $variable_data) {
foreach ($variable_data as $number => $operator) {
switch ($operator) {
case '<':
if (!($variable < $number)) {
myFailFunction();
}
break;
case '<=':
if (!($variable <= $number)) {
myFailFunction();
}
break;
case '>':
if (!($variable < $number)) {
myFailFunction();
}
break;
}
}
}
//if no fail was met run attached function
$func_name = $data[$product]['function'];
$func_name();
//it should run like this too
//$data[$product]['function']();